4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Serializer\Mapping\Loader;
14 use Symfony\Component\Serializer\Exception\MappingException;
15 use Symfony\Component\Serializer\Mapping\AttributeMetadata;
16 use Symfony\Component\Serializer\Mapping\ClassMetadataInterface;
17 use Symfony\Component\Yaml\Parser;
22 * @author Kévin Dunglas <dunglas@gmail.com>
24 class YamlFileLoader extends FileLoader
29 * An array of YAML class descriptions.
38 public function loadClassMetadata(ClassMetadataInterface $classMetadata)
40 if (null === $this->classes) {
41 $this->classes = $this->getClassesFromYaml();
44 if (!$this->classes) {
48 if (!isset($this->classes[$classMetadata->getName()])) {
52 $yaml = $this->classes[$classMetadata->getName()];
54 if (isset($yaml['attributes']) && \is_array($yaml['attributes'])) {
55 $attributesMetadata = $classMetadata->getAttributesMetadata();
57 foreach ($yaml['attributes'] as $attribute => $data) {
58 if (isset($attributesMetadata[$attribute])) {
59 $attributeMetadata = $attributesMetadata[$attribute];
61 $attributeMetadata = new AttributeMetadata($attribute);
62 $classMetadata->addAttributeMetadata($attributeMetadata);
65 if (isset($data['groups'])) {
66 if (!\is_array($data['groups'])) {
67 throw new MappingException(sprintf('The "groups" key must be an array of strings in "%s" for the attribute "%s" of the class "%s".', $this->file, $attribute, $classMetadata->getName()));
70 foreach ($data['groups'] as $group) {
71 if (!\is_string($group)) {
72 throw new MappingException(sprintf('Group names must be strings in "%s" for the attribute "%s" of the class "%s".', $this->file, $attribute, $classMetadata->getName()));
75 $attributeMetadata->addGroup($group);
79 if (isset($data['max_depth'])) {
80 if (!\is_int($data['max_depth'])) {
81 throw new MappingException(sprintf('The "max_depth" value must be an integer in "%s" for the attribute "%s" of the class "%s".', $this->file, $attribute, $classMetadata->getName()));
84 $attributeMetadata->setMaxDepth($data['max_depth']);
93 * Return the names of the classes mapped in this file.
95 * @return string[] The classes names
97 public function getMappedClasses()
99 if (null === $this->classes) {
100 $this->classes = $this->getClassesFromYaml();
103 return array_keys($this->classes);
106 private function getClassesFromYaml()
108 if (!stream_is_local($this->file)) {
109 throw new MappingException(sprintf('This is not a local file "%s".', $this->file));
112 if (null === $this->yamlParser) {
113 $this->yamlParser = new Parser();
116 $classes = $this->yamlParser->parseFile($this->file);
118 if (empty($classes)) {
122 if (!\is_array($classes)) {
123 throw new MappingException(sprintf('The file "%s" must contain a YAML array.', $this->file));