Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Formatter.php
Go to the documentation of this file.
1 <?php
8 
9 class Formatter
10 {
14  private $_indent;
15 
19  public function __construct($indent = " ")
20  {
21  $this->_indent = $indent;
22  }
23 
30  public function format($xmlString)
31  {
32  $xmlDom = new \DOMDocument('1.0');
33  $xmlDom->formatOutput = true;
34  $xmlDom->preserveWhiteSpace = false;
35  $xmlDom->loadXML($xmlString);
36 
37  // replace text in the document with unique placeholders
38  $placeholders = [];
39  $xmlXpath = new \DOMXPath($xmlDom);
41  foreach ($xmlXpath->query('//text() | //comment() | //@*') as $textNode) {
42  $placeholder = \spl_object_hash($textNode);
43  $placeholders[$placeholder] = $textNode->textContent;
44  $textNode->nodeValue = $placeholder;
45  }
46 
47  // render formatted XML structure
48  $result = $xmlDom->saveXML();
49 
50  // replace the default 2-space indents
51  $indent = $this->_indent;
52  $result = \preg_replace_callback(
53  '/^(?:\s{2})+/m',
54  function (array $matches) use ($indent) {
55  $indentCount = \strlen($matches[0]) >> 1;
56  return \str_repeat($indent, $indentCount);
57  },
58  $result
59  );
60 
61  // replace placeholders with values
62  $result = \str_replace(\array_keys($placeholders), \array_values($placeholders), $result);
63 
64  return $result;
65  }
66 }