Converter.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. /**
  3. * Initial configuration data converter. Converts \DOMDocument to array
  4. *
  5. * Copyright © Magento, Inc. All rights reserved.
  6. * See COPYING.txt for license details.
  7. */
  8. namespace Magento\Framework\App\Config\Initial;
  9. class Converter implements \Magento\Framework\Config\ConverterInterface
  10. {
  11. /**
  12. * Node paths to process
  13. *
  14. * @var array
  15. */
  16. protected $_nodeMap = [];
  17. /**
  18. * @var array
  19. */
  20. protected $_metadata = [];
  21. /**
  22. * @param array $nodeMap
  23. */
  24. public function __construct(array $nodeMap = [])
  25. {
  26. $this->_nodeMap = $nodeMap;
  27. }
  28. /**
  29. * Convert config data
  30. *
  31. * @param \DOMDocument $source
  32. * @return array
  33. */
  34. public function convert($source)
  35. {
  36. $output = [];
  37. $xpath = new \DOMXPath($source);
  38. $this->_metadata = [];
  39. /** @var $node \DOMNode */
  40. foreach ($xpath->query(implode(' | ', $this->_nodeMap)) as $node) {
  41. $output = array_merge($output, $this->_convertNode($node));
  42. }
  43. return ['data' => $output, 'metadata' => $this->_metadata];
  44. }
  45. /**
  46. * Convert node oto array
  47. *
  48. * @param \DOMNode $node
  49. * @param string $path
  50. * @return array|string|null
  51. *
  52. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  53. */
  54. protected function _convertNode(\DOMNode $node, $path = '')
  55. {
  56. $output = [];
  57. if ($node->nodeType == XML_ELEMENT_NODE) {
  58. if ($node->hasAttributes()) {
  59. $backendModel = $node->attributes->getNamedItem('backend_model');
  60. if ($backendModel) {
  61. $this->_metadata[$path] = ['backendModel' => $backendModel->nodeValue];
  62. }
  63. }
  64. $nodeData = [];
  65. /** @var $childNode \DOMNode */
  66. foreach ($node->childNodes as $childNode) {
  67. $childrenData = $this->_convertNode($childNode, ($path ? $path . '/' : '') . $childNode->nodeName);
  68. if ($childrenData == null) {
  69. continue;
  70. }
  71. if (is_array($childrenData)) {
  72. $nodeData = array_merge($nodeData, $childrenData);
  73. } else {
  74. $nodeData = $childrenData;
  75. }
  76. }
  77. if (is_array($nodeData) && empty($nodeData)) {
  78. $nodeData = null;
  79. }
  80. $output[$node->nodeName] = $nodeData;
  81. } elseif ($node->nodeType == XML_CDATA_SECTION_NODE || $node->nodeType == XML_TEXT_NODE && trim(
  82. $node->nodeValue
  83. ) != ''
  84. ) {
  85. return $node->nodeValue;
  86. }
  87. return $output;
  88. }
  89. }