0da2f7d690ff668a8773208deae31162e4f87c23
[yaffs-website] / vendor / symfony / serializer / Mapping / Loader / XmlFileLoader.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Symfony\Component\Serializer\Mapping\Loader;
13
14 use Symfony\Component\Config\Util\XmlUtils;
15 use Symfony\Component\Serializer\Exception\MappingException;
16 use Symfony\Component\Serializer\Mapping\AttributeMetadata;
17 use Symfony\Component\Serializer\Mapping\ClassMetadataInterface;
18
19 /**
20  * Loads XML mapping files.
21  *
22  * @author Kévin Dunglas <dunglas@gmail.com>
23  */
24 class XmlFileLoader extends FileLoader
25 {
26     /**
27      * An array of {@class \SimpleXMLElement} instances.
28      *
29      * @var \SimpleXMLElement[]|null
30      */
31     private $classes;
32
33     /**
34      * {@inheritdoc}
35      */
36     public function loadClassMetadata(ClassMetadataInterface $classMetadata)
37     {
38         if (null === $this->classes) {
39             $this->classes = array();
40             $xml = $this->parseFile($this->file);
41
42             foreach ($xml->class as $class) {
43                 $this->classes[(string) $class['name']] = $class;
44             }
45         }
46
47         $attributesMetadata = $classMetadata->getAttributesMetadata();
48
49         if (isset($this->classes[$classMetadata->getName()])) {
50             $xml = $this->classes[$classMetadata->getName()];
51
52             foreach ($xml->attribute as $attribute) {
53                 $attributeName = (string) $attribute['name'];
54
55                 if (isset($attributesMetadata[$attributeName])) {
56                     $attributeMetadata = $attributesMetadata[$attributeName];
57                 } else {
58                     $attributeMetadata = new AttributeMetadata($attributeName);
59                     $classMetadata->addAttributeMetadata($attributeMetadata);
60                 }
61
62                 foreach ($attribute->group as $group) {
63                     $attributeMetadata->addGroup((string) $group);
64                 }
65             }
66
67             return true;
68         }
69
70         return false;
71     }
72
73     /**
74      * Parses a XML File.
75      *
76      * @param string $file Path of file
77      *
78      * @return \SimpleXMLElement
79      *
80      * @throws MappingException
81      */
82     private function parseFile($file)
83     {
84         try {
85             $dom = XmlUtils::loadFile($file, __DIR__.'/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd');
86         } catch (\Exception $e) {
87             throw new MappingException($e->getMessage(), $e->getCode(), $e);
88         }
89
90         return simplexml_import_dom($dom);
91     }
92 }