Formatter.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Developer\Model\Tools;
  7. class Formatter
  8. {
  9. /**
  10. * @var string
  11. */
  12. private $_indent;
  13. /**
  14. * @param string $indent
  15. */
  16. public function __construct($indent = " ")
  17. {
  18. $this->_indent = $indent;
  19. }
  20. /**
  21. * Return a well-formatted XML string
  22. *
  23. * @param string $xmlString
  24. * @return string
  25. */
  26. public function format($xmlString)
  27. {
  28. $xmlDom = new \DOMDocument('1.0');
  29. $xmlDom->formatOutput = true;
  30. $xmlDom->preserveWhiteSpace = false;
  31. $xmlDom->loadXML($xmlString);
  32. // replace text in the document with unique placeholders
  33. $placeholders = [];
  34. $xmlXpath = new \DOMXPath($xmlDom);
  35. /** @var DOMNode $textNode */
  36. foreach ($xmlXpath->query('//text() | //comment() | //@*') as $textNode) {
  37. $placeholder = \spl_object_hash($textNode);
  38. $placeholders[$placeholder] = $textNode->textContent;
  39. $textNode->nodeValue = $placeholder;
  40. }
  41. // render formatted XML structure
  42. $result = $xmlDom->saveXML();
  43. // replace the default 2-space indents
  44. $indent = $this->_indent;
  45. $result = \preg_replace_callback(
  46. '/^(?:\s{2})+/m',
  47. function (array $matches) use ($indent) {
  48. $indentCount = \strlen($matches[0]) >> 1;
  49. return \str_repeat($indent, $indentCount);
  50. },
  51. $result
  52. );
  53. // replace placeholders with values
  54. $result = \str_replace(\array_keys($placeholders), \array_values($placeholders), $result);
  55. return $result;
  56. }
  57. }