Element.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Simplexml;
  7. /**
  8. * Extends SimpleXML to add valuable functionality to \SimpleXMLElement class
  9. *
  10. * @api
  11. * @since 100.0.2
  12. */
  13. class Element extends \SimpleXMLElement
  14. {
  15. /**
  16. * Would keep reference to parent node
  17. *
  18. * If \SimpleXMLElement would support complicated attributes
  19. *
  20. * @todo make use of spl_object_hash to keep global array of simplexml elements
  21. * to emulate complicated attributes
  22. * @var \Magento\Framework\Simplexml\Element
  23. */
  24. protected $_parent = null;
  25. /**
  26. * For future use
  27. *
  28. * @param \Magento\Framework\Simplexml\Element $element
  29. * @return void
  30. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  31. */
  32. public function setParent($element)
  33. {
  34. //$this->_parent = $element;
  35. }
  36. /**
  37. * Returns parent node for the element
  38. *
  39. * Currently using xpath
  40. *
  41. * @throws \InvalidArgumentException
  42. * @return \Magento\Framework\Simplexml\Element
  43. */
  44. public function getParent()
  45. {
  46. if (!empty($this->_parent)) {
  47. $parent = $this->_parent;
  48. } else {
  49. $arr = $this->xpath('..');
  50. if (!isset($arr[0])) {
  51. throw new \InvalidArgumentException('Root node could not be unset.');
  52. }
  53. $parent = $arr[0];
  54. }
  55. return $parent;
  56. }
  57. /**
  58. * Enter description here...
  59. *
  60. * @return boolean
  61. * @SuppressWarnings(PHPMD.UnusedLocalVariable)
  62. */
  63. public function hasChildren()
  64. {
  65. if (!$this->children()) {
  66. return false;
  67. }
  68. // simplexml bug: @attributes is in children() but invisible in foreach
  69. foreach ($this->children() as $k => $child) {
  70. return true;
  71. }
  72. return false;
  73. }
  74. /**
  75. * Returns attribute value by attribute name
  76. *
  77. * @param string $name
  78. * @return string|null
  79. */
  80. public function getAttribute($name)
  81. {
  82. $attrs = $this->attributes();
  83. return isset($attrs[$name]) ? (string)$attrs[$name] : null;
  84. }
  85. /**
  86. * Find a descendant of a node by path
  87. *
  88. * @todo Do we need to make it xpath look-a-like?
  89. * @todo Check if we still need all this and revert to plain XPath if this makes any sense
  90. * @todo param string $path Subset of xpath. Example: "child/grand[@attrName='attrValue']/subGrand"
  91. * @param string $path Example: "child/grand@attrName=attrValue/subGrand" (to make it faster without regex)
  92. * @return \Magento\Framework\Simplexml\Element
  93. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  94. */
  95. public function descend($path)
  96. {
  97. # $node = $this->xpath($path);
  98. # return $node[0];
  99. if (is_array($path)) {
  100. $pathArr = $path;
  101. } else {
  102. // Simple exploding by / does not suffice,
  103. // as an attribute value may contain a / inside
  104. // Note that there are three matches for different kinds of attribute values specification
  105. if (strpos($path, "@") === false) {
  106. $pathArr = explode('/', $path);
  107. } else {
  108. $regex = "#([^@/\\\"]+(?:@[^=/]+=(?:\\\"[^\\\"]*\\\"|[^/]*))?)/?#";
  109. $pathArr = $pathMatches = [];
  110. if (preg_match_all($regex, $path, $pathMatches)) {
  111. $pathArr = $pathMatches[1];
  112. }
  113. }
  114. }
  115. $desc = $this;
  116. foreach ($pathArr as $nodeName) {
  117. if (strpos($nodeName, '@') !== false) {
  118. $a = explode('@', $nodeName);
  119. $b = explode('=', $a[1]);
  120. $nodeName = $a[0];
  121. $attributeName = $b[0];
  122. $attributeValue = $b[1];
  123. //
  124. // Does a very simplistic trimming of attribute value.
  125. //
  126. $attributeValue = trim($attributeValue, '"');
  127. $found = false;
  128. foreach ($desc->{$nodeName} as $subdesc) {
  129. if ((string)$subdesc[$attributeName] === $attributeValue) {
  130. $found = true;
  131. $desc = $subdesc;
  132. break;
  133. }
  134. }
  135. if (!$found) {
  136. $desc = false;
  137. }
  138. } else {
  139. $desc = $desc->{$nodeName};
  140. }
  141. if (!$desc) {
  142. return false;
  143. }
  144. }
  145. return $desc;
  146. }
  147. /**
  148. * Create attribute if it does not exists and set value to it
  149. *
  150. * @param string $name
  151. * @param string $value
  152. * @return void
  153. */
  154. public function setAttribute($name, $value)
  155. {
  156. if (!isset($this->attributes()[$name])) {
  157. $this->addAttribute($name, $value);
  158. }
  159. $this->attributes()[$name] = $value;
  160. }
  161. /**
  162. * Returns the node and children as an array
  163. *
  164. * @return array|string
  165. */
  166. public function asArray()
  167. {
  168. return $this->_asArray();
  169. }
  170. /**
  171. * asArray() analog, but without attributes
  172. * @return array|string
  173. */
  174. public function asCanonicalArray()
  175. {
  176. return $this->_asArray(true);
  177. }
  178. /**
  179. * Returns the node and children as an array
  180. *
  181. * @param bool $isCanonical - whether to ignore attributes
  182. * @return array|string
  183. */
  184. protected function _asArray($isCanonical = false)
  185. {
  186. $result = [];
  187. if (!$isCanonical) {
  188. // add attributes
  189. foreach ($this->attributes() as $attributeName => $attribute) {
  190. if ($attribute) {
  191. $result['@'][$attributeName] = (string)$attribute;
  192. }
  193. }
  194. }
  195. // add children values
  196. if ($this->hasChildren()) {
  197. foreach ($this->children() as $childName => $child) {
  198. $result[$childName] = $child->_asArray($isCanonical);
  199. }
  200. } else {
  201. if (empty($result)) {
  202. // return as string, if nothing was found
  203. $result = (string)$this;
  204. } else {
  205. // value has zero key element
  206. $result[0] = (string)$this;
  207. }
  208. }
  209. return $result;
  210. }
  211. /**
  212. * Makes nicely formatted XML from the node
  213. *
  214. * @param string $filename
  215. * @param int|boolean $level if false
  216. * @return string
  217. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  218. * @SuppressWarnings(PHPMD.NPathComplexity)
  219. */
  220. public function asNiceXml($filename = '', $level = 0)
  221. {
  222. if (is_numeric($level)) {
  223. $pad = str_pad('', $level * 3, ' ', STR_PAD_LEFT);
  224. $nl = "\n";
  225. } else {
  226. $pad = '';
  227. $nl = '';
  228. }
  229. $out = $pad . '<' . $this->getName();
  230. $attributes = $this->attributes();
  231. if ($attributes) {
  232. foreach ($attributes as $key => $value) {
  233. $out .= ' ' . $key . '="' . str_replace('"', '\"', (string)$value) . '"';
  234. }
  235. }
  236. $attributes = $this->attributes('xsi', true);
  237. if ($attributes) {
  238. foreach ($attributes as $key => $value) {
  239. $out .= ' xsi:' . $key . '="' . str_replace('"', '\"', (string)$value) . '"';
  240. }
  241. }
  242. if ($this->hasChildren()) {
  243. $out .= '>';
  244. $value = trim((string)$this);
  245. if (strlen($value)) {
  246. $out .= $this->xmlentities($value);
  247. }
  248. $out .= $nl;
  249. foreach ($this->children() as $child) {
  250. $out .= $child->asNiceXml('', is_numeric($level) ? $level + 1 : true);
  251. }
  252. $out .= $pad . '</' . $this->getName() . '>' . $nl;
  253. } else {
  254. $value = (string)$this;
  255. if (strlen($value)) {
  256. $out .= '>' . $this->xmlentities($value) . '</' . $this->getName() . '>' . $nl;
  257. } else {
  258. $out .= '/>' . $nl;
  259. }
  260. }
  261. if ((0 === $level || false === $level) && !empty($filename)) {
  262. file_put_contents($filename, $out);
  263. }
  264. return $out;
  265. }
  266. /**
  267. * Enter description here...
  268. *
  269. * @param int $level
  270. * @return string
  271. */
  272. public function innerXml($level = 0)
  273. {
  274. $out = '';
  275. foreach ($this->children() as $child) {
  276. $out .= $child->asNiceXml($level);
  277. }
  278. return $out;
  279. }
  280. /**
  281. * Converts meaningful xml characters to xml entities
  282. *
  283. * @param string $value
  284. * @return string
  285. */
  286. public function xmlentities($value = null)
  287. {
  288. if ($value === null) {
  289. $value = $this;
  290. }
  291. $value = (string)$value;
  292. $value = str_replace(
  293. ['&', '"', "'", '<', '>'],
  294. ['&amp;', '&quot;', '&apos;', '&lt;', '&gt;'],
  295. $value
  296. );
  297. return $value;
  298. }
  299. /**
  300. * Appends $source to current node
  301. *
  302. * @param \Magento\Framework\Simplexml\Element $source
  303. * @return $this
  304. */
  305. public function appendChild($source)
  306. {
  307. if ($source->count()) {
  308. $child = $this->addChild($source->getName());
  309. } else {
  310. $child = $this->addChild($source->getName(), $this->xmlentities($source));
  311. }
  312. $child->setParent($this);
  313. $attributes = $source->attributes();
  314. foreach ($attributes as $key => $value) {
  315. $child->addAttribute($key, $this->xmlentities($value));
  316. }
  317. foreach ($source->children() as $sourceChild) {
  318. $child->appendChild($sourceChild);
  319. }
  320. return $this;
  321. }
  322. /**
  323. * Extends current node with xml from $source
  324. *
  325. * If $overwrite is false will merge only missing nodes
  326. * Otherwise will overwrite existing nodes
  327. *
  328. * @param \Magento\Framework\Simplexml\Element $source
  329. * @param boolean $overwrite
  330. * @return $this
  331. */
  332. public function extend($source, $overwrite = false)
  333. {
  334. if (!$source instanceof \Magento\Framework\Simplexml\Element) {
  335. return $this;
  336. }
  337. foreach ($source->children() as $child) {
  338. $this->extendChild($child, $overwrite);
  339. }
  340. return $this;
  341. }
  342. /**
  343. * Extends one node
  344. *
  345. * @param \Magento\Framework\Simplexml\Element $source
  346. * @param boolean $overwrite
  347. * @return $this
  348. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  349. * @SuppressWarnings(PHPMD.UnusedLocalVariable)
  350. */
  351. public function extendChild($source, $overwrite = false)
  352. {
  353. // this will be our new target node
  354. $targetChild = null;
  355. // name of the source node
  356. $sourceName = $source->getName();
  357. // here we have children of our source node
  358. $sourceChildren = $source->children();
  359. if (!$source->hasChildren()) {
  360. // handle string node
  361. if (isset($this->{$sourceName})) {
  362. // if target already has children return without regard
  363. if ($this->{$sourceName}->hasChildren()) {
  364. return $this;
  365. }
  366. if ($overwrite) {
  367. unset($this->{$sourceName});
  368. } else {
  369. return $this;
  370. }
  371. }
  372. $targetChild = $this->addChild($sourceName, $source->xmlentities());
  373. $targetChild->setParent($this);
  374. foreach ($source->attributes() as $key => $value) {
  375. $targetChild->addAttribute($key, $this->xmlentities($value));
  376. }
  377. return $this;
  378. }
  379. if (isset($this->{$sourceName})) {
  380. $targetChild = $this->{$sourceName};
  381. }
  382. if ($targetChild === null) {
  383. // if child target is not found create new and descend
  384. $targetChild = $this->addChild($sourceName);
  385. $targetChild->setParent($this);
  386. foreach ($source->attributes() as $key => $value) {
  387. $targetChild->addAttribute($key, $this->xmlentities($value));
  388. }
  389. }
  390. // finally add our source node children to resulting new target node
  391. foreach ($sourceChildren as $childKey => $childNode) {
  392. $targetChild->extendChild($childNode, $overwrite);
  393. }
  394. return $this;
  395. }
  396. /**
  397. * Set node
  398. *
  399. * @param string $path
  400. * @param string $value
  401. * @param bool $overwrite
  402. * @return $this
  403. */
  404. public function setNode($path, $value, $overwrite = true)
  405. {
  406. $arr1 = explode('/', $path);
  407. $arr = [];
  408. foreach ($arr1 as $v) {
  409. if (!empty($v)) {
  410. $arr[] = $v;
  411. }
  412. }
  413. $last = sizeof($arr) - 1;
  414. $node = $this;
  415. foreach ($arr as $i => $nodeName) {
  416. if ($last === $i) {
  417. if (!isset($node->{$nodeName}) || $overwrite) {
  418. $node->{$nodeName} = $value;
  419. }
  420. } else {
  421. if (!isset($node->{$nodeName})) {
  422. $node = $node->addChild($nodeName);
  423. } else {
  424. $node = $node->{$nodeName};
  425. }
  426. }
  427. }
  428. return $this;
  429. }
  430. /**
  431. * Unset self from the XML-node tree
  432. *
  433. * Note: trying to refer this object as a variable after "unsetting" like this will result in E_WARNING
  434. * @return void
  435. */
  436. public function unsetSelf()
  437. {
  438. $uniqueId = uniqid();
  439. $this['_unique_id'] = $uniqueId;
  440. $children = $this->getParent()->xpath('*');
  441. for ($i = count($children); $i > 0; $i--) {
  442. if ($children[$i - 1][0]['_unique_id'] == $uniqueId) {
  443. unset($children[$i - 1][0]);
  444. return;
  445. }
  446. }
  447. }
  448. }