XmlUtils.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Config\Util;
  11. /**
  12. * XMLUtils is a bunch of utility methods to XML operations.
  13. *
  14. * This class contains static methods only and is not meant to be instantiated.
  15. *
  16. * @author Fabien Potencier <fabien@symfony.com>
  17. * @author Martin Hasoň <martin.hason@gmail.com>
  18. */
  19. class XmlUtils
  20. {
  21. /**
  22. * This class should not be instantiated.
  23. */
  24. private function __construct()
  25. {
  26. }
  27. /**
  28. * Loads an XML file.
  29. *
  30. * @param string $file An XML file path
  31. * @param string|callable|null $schemaOrCallable An XSD schema file path, a callable, or null to disable validation
  32. *
  33. * @return \DOMDocument
  34. *
  35. * @throws \InvalidArgumentException When loading of XML file returns error
  36. * @throws \RuntimeException When DOM extension is missing
  37. */
  38. public static function loadFile($file, $schemaOrCallable = null)
  39. {
  40. if (!\extension_loaded('dom')) {
  41. throw new \RuntimeException('Extension DOM is required.');
  42. }
  43. $content = @file_get_contents($file);
  44. if ('' === trim($content)) {
  45. throw new \InvalidArgumentException(sprintf('File %s does not contain valid XML, it is empty.', $file));
  46. }
  47. $internalErrors = libxml_use_internal_errors(true);
  48. $disableEntities = libxml_disable_entity_loader(true);
  49. libxml_clear_errors();
  50. $dom = new \DOMDocument();
  51. $dom->validateOnParse = true;
  52. if (!$dom->loadXML($content, LIBXML_NONET | (\defined('LIBXML_COMPACT') ? LIBXML_COMPACT : 0))) {
  53. libxml_disable_entity_loader($disableEntities);
  54. throw new \InvalidArgumentException(implode("\n", static::getXmlErrors($internalErrors)));
  55. }
  56. $dom->normalizeDocument();
  57. libxml_use_internal_errors($internalErrors);
  58. libxml_disable_entity_loader($disableEntities);
  59. foreach ($dom->childNodes as $child) {
  60. if (XML_DOCUMENT_TYPE_NODE === $child->nodeType) {
  61. throw new \InvalidArgumentException('Document types are not allowed.');
  62. }
  63. }
  64. if (null !== $schemaOrCallable) {
  65. $internalErrors = libxml_use_internal_errors(true);
  66. libxml_clear_errors();
  67. $e = null;
  68. if (\is_callable($schemaOrCallable)) {
  69. try {
  70. $valid = \call_user_func($schemaOrCallable, $dom, $internalErrors);
  71. } catch (\Exception $e) {
  72. $valid = false;
  73. }
  74. } elseif (!\is_array($schemaOrCallable) && is_file((string) $schemaOrCallable)) {
  75. $schemaSource = file_get_contents((string) $schemaOrCallable);
  76. $valid = @$dom->schemaValidateSource($schemaSource);
  77. } else {
  78. libxml_use_internal_errors($internalErrors);
  79. throw new \InvalidArgumentException('The schemaOrCallable argument has to be a valid path to XSD file or callable.');
  80. }
  81. if (!$valid) {
  82. $messages = static::getXmlErrors($internalErrors);
  83. if (empty($messages)) {
  84. $messages = array(sprintf('The XML file "%s" is not valid.', $file));
  85. }
  86. throw new \InvalidArgumentException(implode("\n", $messages), 0, $e);
  87. }
  88. }
  89. libxml_clear_errors();
  90. libxml_use_internal_errors($internalErrors);
  91. return $dom;
  92. }
  93. /**
  94. * Converts a \DOMElement object to a PHP array.
  95. *
  96. * The following rules applies during the conversion:
  97. *
  98. * * Each tag is converted to a key value or an array
  99. * if there is more than one "value"
  100. *
  101. * * The content of a tag is set under a "value" key (<foo>bar</foo>)
  102. * if the tag also has some nested tags
  103. *
  104. * * The attributes are converted to keys (<foo foo="bar"/>)
  105. *
  106. * * The nested-tags are converted to keys (<foo><foo>bar</foo></foo>)
  107. *
  108. * @param \DOMElement $element A \DOMElement instance
  109. * @param bool $checkPrefix Check prefix in an element or an attribute name
  110. *
  111. * @return array A PHP array
  112. */
  113. public static function convertDomElementToArray(\DOMElement $element, $checkPrefix = true)
  114. {
  115. $prefix = (string) $element->prefix;
  116. $empty = true;
  117. $config = array();
  118. foreach ($element->attributes as $name => $node) {
  119. if ($checkPrefix && !\in_array((string) $node->prefix, array('', $prefix), true)) {
  120. continue;
  121. }
  122. $config[$name] = static::phpize($node->value);
  123. $empty = false;
  124. }
  125. $nodeValue = false;
  126. foreach ($element->childNodes as $node) {
  127. if ($node instanceof \DOMText) {
  128. if ('' !== trim($node->nodeValue)) {
  129. $nodeValue = trim($node->nodeValue);
  130. $empty = false;
  131. }
  132. } elseif ($checkPrefix && $prefix != (string) $node->prefix) {
  133. continue;
  134. } elseif (!$node instanceof \DOMComment) {
  135. $value = static::convertDomElementToArray($node, $checkPrefix);
  136. $key = $node->localName;
  137. if (isset($config[$key])) {
  138. if (!\is_array($config[$key]) || !\is_int(key($config[$key]))) {
  139. $config[$key] = array($config[$key]);
  140. }
  141. $config[$key][] = $value;
  142. } else {
  143. $config[$key] = $value;
  144. }
  145. $empty = false;
  146. }
  147. }
  148. if (false !== $nodeValue) {
  149. $value = static::phpize($nodeValue);
  150. if (\count($config)) {
  151. $config['value'] = $value;
  152. } else {
  153. $config = $value;
  154. }
  155. }
  156. return !$empty ? $config : null;
  157. }
  158. /**
  159. * Converts an xml value to a PHP type.
  160. *
  161. * @param mixed $value
  162. *
  163. * @return mixed
  164. */
  165. public static function phpize($value)
  166. {
  167. $value = (string) $value;
  168. $lowercaseValue = strtolower($value);
  169. switch (true) {
  170. case 'null' === $lowercaseValue:
  171. return;
  172. case ctype_digit($value):
  173. $raw = $value;
  174. $cast = (int) $value;
  175. return '0' == $value[0] ? octdec($value) : (((string) $raw === (string) $cast) ? $cast : $raw);
  176. case isset($value[1]) && '-' === $value[0] && ctype_digit(substr($value, 1)):
  177. $raw = $value;
  178. $cast = (int) $value;
  179. return '0' == $value[1] ? octdec($value) : (((string) $raw === (string) $cast) ? $cast : $raw);
  180. case 'true' === $lowercaseValue:
  181. return true;
  182. case 'false' === $lowercaseValue:
  183. return false;
  184. case isset($value[1]) && '0b' == $value[0].$value[1]:
  185. return bindec($value);
  186. case is_numeric($value):
  187. return '0x' === $value[0].$value[1] ? hexdec($value) : (float) $value;
  188. case preg_match('/^0x[0-9a-f]++$/i', $value):
  189. return hexdec($value);
  190. case preg_match('/^(-|\+)?[0-9]+(\.[0-9]+)?$/', $value):
  191. return (float) $value;
  192. default:
  193. return $value;
  194. }
  195. }
  196. protected static function getXmlErrors($internalErrors)
  197. {
  198. $errors = array();
  199. foreach (libxml_get_errors() as $error) {
  200. $errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)',
  201. LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR',
  202. $error->code,
  203. trim($error->message),
  204. $error->file ?: 'n/a',
  205. $error->line,
  206. $error->column
  207. );
  208. }
  209. libxml_clear_errors();
  210. libxml_use_internal_errors($internalErrors);
  211. return $errors;
  212. }
  213. }