Completed
Push — master ( 094d7a...9edd9c )
by Philip
04:06
created

YamlDriver::getOrCreatePropertyMetadata()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 6
cts 6
cp 1
rs 9.9
c 0
b 0
f 0
cc 2
nc 2
nop 2
crap 2
1
<?php
2
3
namespace Dontdrinkandroot\RestBundle\Metadata\Driver;
4
5
use Dontdrinkandroot\RestBundle\Metadata\Annotation\Method;
6
use Dontdrinkandroot\RestBundle\Metadata\Annotation\Postable;
7
use Dontdrinkandroot\RestBundle\Metadata\Annotation\Puttable;
8
use Dontdrinkandroot\RestBundle\Metadata\ClassMetadata;
9
use Dontdrinkandroot\RestBundle\Metadata\PropertyMetadata;
10
use Metadata\Driver\AbstractFileDriver;
11
use Metadata\Driver\DriverInterface;
12
use Metadata\Driver\FileLocatorInterface;
13
use Symfony\Component\Yaml\Yaml;
14
15
class YamlDriver extends AbstractFileDriver
16
{
17
    /**
18
     * @var DriverInterface
19
     */
20
    private $doctrineDriver;
21
22 88
    public function __construct(FileLocatorInterface $locator, DriverInterface $doctrineDriver)
23
    {
24 88
        parent::__construct($locator);
25 88
        $this->doctrineDriver = $doctrineDriver;
26 88
    }
27
28
    /**
29
     * {@inheritdoc}
30
     */
31 52
    protected function loadMetadataFromFile(\ReflectionClass $class, $file)
32
    {
33
        /** @var ClassMetadata $ddrRestClassMetadata */
34 52
        $classMetadata = $this->doctrineDriver->loadMetadataForClass($class);
35 52
        if (null === $classMetadata) {
36
            $classMetadata = new ClassMetadata($class->getName());
37
        }
38
39 52
        $config = Yaml::parse(file_get_contents($file));
40 52
        $className = key($config);
41
42 52
        if ($className !== $class->name) {
43
            throw new \RuntimeException(
44
                sprintf('Class definition mismatch for "%s" in "%s": %s', $class->getName(), $file, key($config))
45
            );
46
        }
47
48 52
        $config = $config[$className];
49 52
        if (!is_array($config)) {
50
            $config = [];
51
        }
52
53 52
        if (array_key_exists('rootResource', $config) && true === $config['rootResource']) {
54 52
            $classMetadata->setRestResource(true);
55
        }
56 52
        if (array_key_exists('controller', $config)) {
57
            $classMetadata->controller = $config['controller'];
0 ignored issues
show
Bug introduced by
The property controller does not seem to exist in Metadata\ClassMetadata.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
58
        }
59 52
        if (array_key_exists('idField', $config)) {
60
            $classMetadata->idField = $config['idField'];
0 ignored issues
show
Bug introduced by
The property idField does not seem to exist in Metadata\ClassMetadata.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
61
        }
62 52
        if (array_key_exists('pathPrefix', $config)) {
63
            $classMetadata->pathPrefix = $config['pathPrefix'];
0 ignored issues
show
Bug introduced by
The property pathPrefix does not seem to exist in Metadata\ClassMetadata.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
64
        }
65 52
        if (array_key_exists('namePrefix', $config)) {
66
            $classMetadata->namePrefix = $config['namePrefix'];
0 ignored issues
show
Bug introduced by
The property namePrefix does not seem to exist in Metadata\ClassMetadata.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
67
        }
68
69 52
        $classMetadata->setMethods($this->parseMethods($config));
70
71 52
        $fieldConfigs = [];
72 52
        if (array_key_exists('fields', $config)) {
73 52
            $fieldConfigs = $config['fields'];
74
        }
75
76 52
        foreach ($class->getProperties() as $reflectionProperty) {
77
78 52
            $propertyName = $reflectionProperty->getName();
79 52
            $propertyMetadata = $this->getOrCreatePropertyMetadata($classMetadata, $propertyName);
0 ignored issues
show
Compatibility introduced by
$classMetadata of type object<Metadata\ClassMetadata> is not a sub-type of object<Dontdrinkandroot\...Metadata\ClassMetadata>. It seems like you assume a child class of the class Metadata\ClassMetadata to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
80
81 52
            if (array_key_exists($propertyName, $fieldConfigs)) {
82 52
                $fieldConfig = $fieldConfigs[$propertyName];
83 52
                $this->parseFieldConfig($propertyName, $fieldConfig, $propertyMetadata);
84 52
                unset($fieldConfigs[$propertyName]);
85
            }
86
87 52
            $classMetadata->addPropertyMetadata($propertyMetadata);
88
        }
89
90
        /* Parse unbacked field definitions */
91 52
        foreach ($fieldConfigs as $name => $fieldConfig) {
92 32
            $propertyMetadata = $this->getOrCreatePropertyMetadata($classMetadata, $name);
0 ignored issues
show
Compatibility introduced by
$classMetadata of type object<Metadata\ClassMetadata> is not a sub-type of object<Dontdrinkandroot\...Metadata\ClassMetadata>. It seems like you assume a child class of the class Metadata\ClassMetadata to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
93 32
            $this->parseFieldConfig($name, $fieldConfig, $propertyMetadata);
94 32
            $classMetadata->addPropertyMetadata($propertyMetadata);
95
        }
96
97 52
        return $classMetadata;
98
    }
99
100 52
    protected function parseFieldConfig(string $name, array $fieldConfig, PropertyMetadata $propertyMetadata): void
101
    {
102 52
        $propertyMetadata->setPostable(Postable::parse($fieldConfig['postable'] ?? null));
103 52
        $propertyMetadata->setPuttable(Puttable::parse($fieldConfig['puttable'] ?? null));
104
105 52
        if (null !== $value = $fieldConfig['type'] ?? null) {
106
            $propertyMetadata->setType($value);
107
        }
108
109 52
        if (null !== $value = $this->getBool('excluded', $fieldConfig)) {
110 32
            $propertyMetadata->setExcluded($value);
111
        }
112
113 52
        if (null !== $value = $this->getBool('virtual', $fieldConfig)) {
114 30
            $propertyMetadata->setVirtual($value);
115
        }
116
117 52
        if (null !== $subResourceConfig = $fieldConfig['subResource'] ?? null) {
118 50
            $propertyMetadata->setSubResource(true);
119 50
            $propertyMetadata->setMethods($this->parseMethods($subResourceConfig));
0 ignored issues
show
Documentation introduced by
$this->parseMethods($subResourceConfig) is of type null|array, but the function expects a array<integer,object<Don...ata\Annotation\Method>>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
120
        }
121
122 52
        if (array_key_exists('includable', $fieldConfig)) {
123 50
            $value = $fieldConfig['includable'];
124 50
            if (is_array($value)) {
125 32
                $propertyMetadata->setIncludable(true);
126 32
                $propertyMetadata->setIncludablePaths($value);
127 50
            } elseif (true === $value) {
128 50
                $propertyMetadata->setIncludable(true);
129 50
                $propertyMetadata->setIncludablePaths([$name]);
130
            }
131
        }
132 52
    }
133
134 52
    private function getBool(string $key, array $haystack, bool $required = false)
135
    {
136 52
        $value = $this->getArrayValue($key, $haystack, $required);
137 52
        if (null === $value) {
138 52
            return null;
139
        }
140
141 32
        if (!is_bool($value)) {
142
            throw new \RuntimeException(sprintf('Value %s must be of type bool', $key));
143
        }
144
145 32
        return $value;
146
    }
147
148 52
    private function getArrayValue(string $key, array $haystack, bool $required = false)
149
    {
150 52
        if (!array_key_exists($key, $haystack)) {
151 52
            if ($required) {
152
                throw new \RuntimeException(sprintf('Value %s is required', $key));
153
            }
154
155 52
            return null;
156
        }
157
158 32
        return $haystack[$key];
159
    }
160
161
    /**
162
     * {@inheritdoc}
163
     */
164 88
    protected function getExtension()
165
    {
166 88
        return 'rest.yml';
167
    }
168
169 52
    protected function getOrCreatePropertyMetadata(ClassMetadata $classMetadata, $propertyName): PropertyMetadata
170
    {
171 52
        $propertyMetadata = $classMetadata->getPropertyMetadata($propertyName);
172 52
        if (null === $propertyMetadata) {
173 32
            $propertyMetadata = new PropertyMetadata($classMetadata->name, $propertyName);
174
175 32
            return $propertyMetadata;
176
        }
177
178 50
        return $propertyMetadata;
179
    }
180
181
    /**
182
     * @param array $config
183
     *
184
     * @return Method[]
185
     */
186 52
    private function parseMethods(array $config)
187
    {
188 52
        if (!array_key_exists('methods', $config)) {
189
            return null;
190
        }
191
192 52
        $methods = [];
193 52
        $methodsConfig = $config['methods'];
194 52
        foreach ($methodsConfig as $name => $config) {
195 52
            $method = Method::parse($name, $config);
196 52
            $methods[$method->name] = $method;
197
        }
198
199 52
        return $methods;
200
    }
201
}
202