XmlFileLoader.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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\Serializer\Mapping\Loader;
  11. use Symfony\Component\Config\Util\XmlUtils;
  12. use Symfony\Component\Serializer\Exception\MappingException;
  13. use Symfony\Component\Serializer\Mapping\AttributeMetadata;
  14. use Symfony\Component\Serializer\Mapping\ClassMetadataInterface;
  15. /**
  16. * Loads XML mapping files.
  17. *
  18. * @author Kévin Dunglas <dunglas@gmail.com>
  19. */
  20. class XmlFileLoader extends FileLoader
  21. {
  22. /**
  23. * An array of {@class \SimpleXMLElement} instances.
  24. *
  25. * @var \SimpleXMLElement[]|null
  26. */
  27. private $classes;
  28. /**
  29. * {@inheritdoc}
  30. */
  31. public function loadClassMetadata(ClassMetadataInterface $classMetadata)
  32. {
  33. if (null === $this->classes) {
  34. $this->classes = array();
  35. $xml = $this->parseFile($this->file);
  36. foreach ($xml->class as $class) {
  37. $this->classes[(string) $class['name']] = $class;
  38. }
  39. }
  40. $attributesMetadata = $classMetadata->getAttributesMetadata();
  41. if (isset($this->classes[$classMetadata->getName()])) {
  42. $xml = $this->classes[$classMetadata->getName()];
  43. foreach ($xml->attribute as $attribute) {
  44. $attributeName = (string) $attribute['name'];
  45. if (isset($attributesMetadata[$attributeName])) {
  46. $attributeMetadata = $attributesMetadata[$attributeName];
  47. } else {
  48. $attributeMetadata = new AttributeMetadata($attributeName);
  49. $classMetadata->addAttributeMetadata($attributeMetadata);
  50. }
  51. foreach ($attribute->group as $group) {
  52. $attributeMetadata->addGroup((string) $group);
  53. }
  54. if (isset($attribute['max-depth'])) {
  55. $attributeMetadata->setMaxDepth((int) $attribute['max-depth']);
  56. }
  57. }
  58. return true;
  59. }
  60. return false;
  61. }
  62. /**
  63. * Parses a XML File.
  64. *
  65. * @param string $file Path of file
  66. *
  67. * @return \SimpleXMLElement
  68. *
  69. * @throws MappingException
  70. */
  71. private function parseFile($file)
  72. {
  73. try {
  74. $dom = XmlUtils::loadFile($file, __DIR__.'/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd');
  75. } catch (\Exception $e) {
  76. throw new MappingException($e->getMessage(), $e->getCode(), $e);
  77. }
  78. return simplexml_import_dom($dom);
  79. }
  80. }