XmlUtils.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. */
  37. public static function loadFile($file, $schemaOrCallable = null)
  38. {
  39. $content = @file_get_contents($file);
  40. if ('' === trim($content)) {
  41. throw new \InvalidArgumentException(sprintf('File %s does not contain valid XML, it is empty.', $file));
  42. }
  43. $internalErrors = libxml_use_internal_errors(true);
  44. $disableEntities = libxml_disable_entity_loader(true);
  45. libxml_clear_errors();
  46. $dom = new \DOMDocument();
  47. $dom->validateOnParse = true;
  48. if (!$dom->loadXML($content, LIBXML_NONET | (defined('LIBXML_COMPACT') ? LIBXML_COMPACT : 0))) {
  49. libxml_disable_entity_loader($disableEntities);
  50. throw new \InvalidArgumentException(implode("\n", static::getXmlErrors($internalErrors)));
  51. }
  52. $dom->normalizeDocument();
  53. libxml_use_internal_errors($internalErrors);
  54. libxml_disable_entity_loader($disableEntities);
  55. foreach ($dom->childNodes as $child) {
  56. if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) {
  57. throw new \InvalidArgumentException('Document types are not allowed.');
  58. }
  59. }
  60. if (null !== $schemaOrCallable) {
  61. $internalErrors = libxml_use_internal_errors(true);
  62. libxml_clear_errors();
  63. $e = null;
  64. if (is_callable($schemaOrCallable)) {
  65. try {
  66. $valid = call_user_func($schemaOrCallable, $dom, $internalErrors);
  67. } catch (\Exception $e) {
  68. $valid = false;
  69. }
  70. } elseif (!is_array($schemaOrCallable) && is_file((string) $schemaOrCallable)) {
  71. $schemaSource = file_get_contents((string) $schemaOrCallable);
  72. $valid = @$dom->schemaValidateSource($schemaSource);
  73. } else {
  74. libxml_use_internal_errors($internalErrors);
  75. throw new \InvalidArgumentException('The schemaOrCallable argument has to be a valid path to XSD file or callable.');
  76. }
  77. if (!$valid) {
  78. $messages = static::getXmlErrors($internalErrors);
  79. if (empty($messages)) {
  80. $messages = array(sprintf('The XML file "%s" is not valid.', $file));
  81. }
  82. throw new \InvalidArgumentException(implode("\n", $messages), 0, $e);
  83. }
  84. }
  85. libxml_clear_errors();
  86. libxml_use_internal_errors($internalErrors);
  87. return $dom;
  88. }
  89. /**
  90. * Converts a \DomElement object to a PHP array.
  91. *
  92. * The following rules applies during the conversion:
  93. *
  94. * * Each tag is converted to a key value or an array
  95. * if there is more than one "value"
  96. *
  97. * * The content of a tag is set under a "value" key (<foo>bar</foo>)
  98. * if the tag also has some nested tags
  99. *
  100. * * The attributes are converted to keys (<foo foo="bar"/>)
  101. *
  102. * * The nested-tags are converted to keys (<foo><foo>bar</foo></foo>)
  103. *
  104. * @param \DomElement $element A \DomElement instance
  105. * @param bool $checkPrefix Check prefix in an element or an attribute name
  106. *
  107. * @return array A PHP array
  108. */
  109. public static function convertDomElementToArray(\DOMElement $element, $checkPrefix = true)
  110. {
  111. $prefix = (string) $element->prefix;
  112. $empty = true;
  113. $config = array();
  114. foreach ($element->attributes as $name => $node) {
  115. if ($checkPrefix && !in_array((string) $node->prefix, array('', $prefix), true)) {
  116. continue;
  117. }
  118. $config[$name] = static::phpize($node->value);
  119. $empty = false;
  120. }
  121. $nodeValue = false;
  122. foreach ($element->childNodes as $node) {
  123. if ($node instanceof \DOMText) {
  124. if ('' !== trim($node->nodeValue)) {
  125. $nodeValue = trim($node->nodeValue);
  126. $empty = false;
  127. }
  128. } elseif ($checkPrefix && $prefix != (string) $node->prefix) {
  129. continue;
  130. } elseif (!$node instanceof \DOMComment) {
  131. $value = static::convertDomElementToArray($node, $checkPrefix);
  132. $key = $node->localName;
  133. if (isset($config[$key])) {
  134. if (!is_array($config[$key]) || !is_int(key($config[$key]))) {
  135. $config[$key] = array($config[$key]);
  136. }
  137. $config[$key][] = $value;
  138. } else {
  139. $config[$key] = $value;
  140. }
  141. $empty = false;
  142. }
  143. }
  144. if (false !== $nodeValue) {
  145. $value = static::phpize($nodeValue);
  146. if (count($config)) {
  147. $config['value'] = $value;
  148. } else {
  149. $config = $value;
  150. }
  151. }
  152. return !$empty ? $config : null;
  153. }
  154. /**
  155. * Converts an xml value to a PHP type.
  156. *
  157. * @param mixed $value
  158. *
  159. * @return mixed
  160. */
  161. public static function phpize($value)
  162. {
  163. $value = (string) $value;
  164. $lowercaseValue = strtolower($value);
  165. switch (true) {
  166. case 'null' === $lowercaseValue:
  167. return;
  168. case ctype_digit($value):
  169. $raw = $value;
  170. $cast = (int) $value;
  171. return '0' == $value[0] ? octdec($value) : (((string) $raw === (string) $cast) ? $cast : $raw);
  172. case isset($value[1]) && '-' === $value[0] && ctype_digit(substr($value, 1)):
  173. $raw = $value;
  174. $cast = (int) $value;
  175. return '0' == $value[1] ? octdec($value) : (((string) $raw === (string) $cast) ? $cast : $raw);
  176. case 'true' === $lowercaseValue:
  177. return true;
  178. case 'false' === $lowercaseValue:
  179. return false;
  180. case isset($value[1]) && '0b' == $value[0].$value[1]:
  181. return bindec($value);
  182. case is_numeric($value):
  183. return '0x' === $value[0].$value[1] ? hexdec($value) : (float) $value;
  184. case preg_match('/^0x[0-9a-f]++$/i', $value):
  185. return hexdec($value);
  186. case preg_match('/^(-|\+)?[0-9]+(\.[0-9]+)?$/', $value):
  187. return (float) $value;
  188. default:
  189. return $value;
  190. }
  191. }
  192. protected static function getXmlErrors($internalErrors)
  193. {
  194. $errors = array();
  195. foreach (libxml_get_errors() as $error) {
  196. $errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)',
  197. LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR',
  198. $error->code,
  199. trim($error->message),
  200. $error->file ?: 'n/a',
  201. $error->line,
  202. $error->column
  203. );
  204. }
  205. libxml_clear_errors();
  206. libxml_use_internal_errors($internalErrors);
  207. return $errors;
  208. }
  209. }