XmlUtils.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. use Symfony\Component\Config\Util\Exception\InvalidXmlException;
  12. use Symfony\Component\Config\Util\Exception\XmlParsingException;
  13. /**
  14. * XMLUtils is a bunch of utility methods to XML operations.
  15. *
  16. * This class contains static methods only and is not meant to be instantiated.
  17. *
  18. * @author Fabien Potencier <fabien@symfony.com>
  19. * @author Martin Hasoň <martin.hason@gmail.com>
  20. * @author Ole Rößner <ole@roessner.it>
  21. */
  22. class XmlUtils
  23. {
  24. /**
  25. * This class should not be instantiated.
  26. */
  27. private function __construct()
  28. {
  29. }
  30. /**
  31. * Parses an XML string.
  32. *
  33. * @param string $content An XML string
  34. * @param string|callable|null $schemaOrCallable An XSD schema file path, a callable, or null to disable validation
  35. *
  36. * @return \DOMDocument
  37. *
  38. * @throws XmlParsingException When parsing of XML file returns error
  39. * @throws InvalidXmlException When parsing of XML with schema or callable produces any errors unrelated to the XML parsing itself
  40. * @throws \RuntimeException When DOM extension is missing
  41. */
  42. public static function parse($content, $schemaOrCallable = null)
  43. {
  44. if (!\extension_loaded('dom')) {
  45. throw new \LogicException('Extension DOM is required.');
  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 XmlParsingException(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 XmlParsingException('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 = $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 XmlParsingException('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. throw new InvalidXmlException('The XML is not valid.', 0, $e);
  85. }
  86. throw new XmlParsingException(implode("\n", $messages), 0, $e);
  87. }
  88. }
  89. libxml_clear_errors();
  90. libxml_use_internal_errors($internalErrors);
  91. return $dom;
  92. }
  93. /**
  94. * Loads an XML file.
  95. *
  96. * @param string $file An XML file path
  97. * @param string|callable|null $schemaOrCallable An XSD schema file path, a callable, or null to disable validation
  98. *
  99. * @return \DOMDocument
  100. *
  101. * @throws \InvalidArgumentException When loading of XML file returns error
  102. * @throws XmlParsingException When XML parsing returns any errors
  103. * @throws \RuntimeException When DOM extension is missing
  104. */
  105. public static function loadFile($file, $schemaOrCallable = null)
  106. {
  107. if (!is_file($file)) {
  108. throw new \InvalidArgumentException(sprintf('Resource "%s" is not a file.', $file));
  109. }
  110. if (!is_readable($file)) {
  111. throw new \InvalidArgumentException(sprintf('File "%s" is not readable.', $file));
  112. }
  113. $content = @file_get_contents($file);
  114. if ('' === trim($content)) {
  115. throw new \InvalidArgumentException(sprintf('File "%s" does not contain valid XML, it is empty.', $file));
  116. }
  117. try {
  118. return static::parse($content, $schemaOrCallable);
  119. } catch (InvalidXmlException $e) {
  120. throw new XmlParsingException(sprintf('The XML file "%s" is not valid.', $file), 0, $e->getPrevious());
  121. }
  122. }
  123. /**
  124. * Converts a \DOMElement object to a PHP array.
  125. *
  126. * The following rules applies during the conversion:
  127. *
  128. * * Each tag is converted to a key value or an array
  129. * if there is more than one "value"
  130. *
  131. * * The content of a tag is set under a "value" key (<foo>bar</foo>)
  132. * if the tag also has some nested tags
  133. *
  134. * * The attributes are converted to keys (<foo foo="bar"/>)
  135. *
  136. * * The nested-tags are converted to keys (<foo><foo>bar</foo></foo>)
  137. *
  138. * @param \DOMElement $element A \DOMElement instance
  139. * @param bool $checkPrefix Check prefix in an element or an attribute name
  140. *
  141. * @return mixed
  142. */
  143. public static function convertDomElementToArray(\DOMElement $element, $checkPrefix = true)
  144. {
  145. $prefix = (string) $element->prefix;
  146. $empty = true;
  147. $config = [];
  148. foreach ($element->attributes as $name => $node) {
  149. if ($checkPrefix && !\in_array((string) $node->prefix, ['', $prefix], true)) {
  150. continue;
  151. }
  152. $config[$name] = static::phpize($node->value);
  153. $empty = false;
  154. }
  155. $nodeValue = false;
  156. foreach ($element->childNodes as $node) {
  157. if ($node instanceof \DOMText) {
  158. if ('' !== trim($node->nodeValue)) {
  159. $nodeValue = trim($node->nodeValue);
  160. $empty = false;
  161. }
  162. } elseif ($checkPrefix && $prefix != (string) $node->prefix) {
  163. continue;
  164. } elseif (!$node instanceof \DOMComment) {
  165. $value = static::convertDomElementToArray($node, $checkPrefix);
  166. $key = $node->localName;
  167. if (isset($config[$key])) {
  168. if (!\is_array($config[$key]) || !\is_int(key($config[$key]))) {
  169. $config[$key] = [$config[$key]];
  170. }
  171. $config[$key][] = $value;
  172. } else {
  173. $config[$key] = $value;
  174. }
  175. $empty = false;
  176. }
  177. }
  178. if (false !== $nodeValue) {
  179. $value = static::phpize($nodeValue);
  180. if (\count($config)) {
  181. $config['value'] = $value;
  182. } else {
  183. $config = $value;
  184. }
  185. }
  186. return !$empty ? $config : null;
  187. }
  188. /**
  189. * Converts an xml value to a PHP type.
  190. *
  191. * @param mixed $value
  192. *
  193. * @return mixed
  194. */
  195. public static function phpize($value)
  196. {
  197. $value = (string) $value;
  198. $lowercaseValue = strtolower($value);
  199. switch (true) {
  200. case 'null' === $lowercaseValue:
  201. return null;
  202. case ctype_digit($value):
  203. $raw = $value;
  204. $cast = (int) $value;
  205. return '0' == $value[0] ? octdec($value) : (((string) $raw === (string) $cast) ? $cast : $raw);
  206. case isset($value[1]) && '-' === $value[0] && ctype_digit(substr($value, 1)):
  207. $raw = $value;
  208. $cast = (int) $value;
  209. return '0' == $value[1] ? octdec($value) : (((string) $raw === (string) $cast) ? $cast : $raw);
  210. case 'true' === $lowercaseValue:
  211. return true;
  212. case 'false' === $lowercaseValue:
  213. return false;
  214. case isset($value[1]) && '0b' == $value[0].$value[1] && preg_match('/^0b[01]*$/', $value):
  215. return bindec($value);
  216. case is_numeric($value):
  217. return '0x' === $value[0].$value[1] ? hexdec($value) : (float) $value;
  218. case preg_match('/^0x[0-9a-f]++$/i', $value):
  219. return hexdec($value);
  220. case preg_match('/^[+-]?[0-9]+(\.[0-9]+)?$/', $value):
  221. return (float) $value;
  222. default:
  223. return $value;
  224. }
  225. }
  226. protected static function getXmlErrors($internalErrors)
  227. {
  228. $errors = [];
  229. foreach (libxml_get_errors() as $error) {
  230. $errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)',
  231. LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR',
  232. $error->code,
  233. trim($error->message),
  234. $error->file ?: 'n/a',
  235. $error->line,
  236. $error->column
  237. );
  238. }
  239. libxml_clear_errors();
  240. libxml_use_internal_errors($internalErrors);
  241. return $errors;
  242. }
  243. }