Xml.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * Zend Framework (http://framework.zend.com/)
  4. *
  5. * @link http://github.com/zendframework/zf2 for the canonical source repository
  6. * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
  7. * @license http://framework.zend.com/license/new-bsd New BSD License
  8. */
  9. namespace Zend\Config\Writer;
  10. use XMLWriter;
  11. use Zend\Config\Exception;
  12. class Xml extends AbstractWriter
  13. {
  14. /**
  15. * processConfig(): defined by AbstractWriter.
  16. *
  17. * @param array $config
  18. * @return string
  19. */
  20. public function processConfig(array $config)
  21. {
  22. $writer = new XMLWriter('UTF-8');
  23. $writer->openMemory();
  24. $writer->setIndent(true);
  25. $writer->setIndentString(str_repeat(' ', 4));
  26. $writer->startDocument('1.0', 'UTF-8');
  27. $writer->startElement('zend-config');
  28. foreach ($config as $sectionName => $data) {
  29. if (!is_array($data)) {
  30. $writer->writeElement($sectionName, (string) $data);
  31. } else {
  32. $this->addBranch($sectionName, $data, $writer);
  33. }
  34. }
  35. $writer->endElement();
  36. $writer->endDocument();
  37. return $writer->outputMemory();
  38. }
  39. /**
  40. * Add a branch to an XML object recursively.
  41. *
  42. * @param string $branchName
  43. * @param array $config
  44. * @param XMLWriter $writer
  45. * @return void
  46. * @throws Exception\RuntimeException
  47. */
  48. protected function addBranch($branchName, array $config, XMLWriter $writer)
  49. {
  50. $branchType = null;
  51. foreach ($config as $key => $value) {
  52. if ($branchType === null) {
  53. if (is_numeric($key)) {
  54. $branchType = 'numeric';
  55. } else {
  56. $writer->startElement($branchName);
  57. $branchType = 'string';
  58. }
  59. } elseif ($branchType !== (is_numeric($key) ? 'numeric' : 'string')) {
  60. throw new Exception\RuntimeException('Mixing of string and numeric keys is not allowed');
  61. }
  62. if ($branchType === 'numeric') {
  63. if (is_array($value)) {
  64. $this->addBranch($value, $value, $writer);
  65. } else {
  66. $writer->writeElement($branchName, (string) $value);
  67. }
  68. } else {
  69. if (is_array($value)) {
  70. $this->addBranch($key, $value, $writer);
  71. } else {
  72. $writer->writeElement($key, (string) $value);
  73. }
  74. }
  75. }
  76. if ($branchType === 'string') {
  77. $writer->endElement();
  78. }
  79. }
  80. }