Completed
Push — master ( 2afc29...29656f )
by Philip
06:07
created

YamlDriver::parseMethods()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 9
cts 9
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 9
nc 3
nop 1
crap 3
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 100
    public function __construct(FileLocatorInterface $locator, DriverInterface $doctrineDriver)
23
    {
24 100
        parent::__construct($locator);
25 100
        $this->doctrineDriver = $doctrineDriver;
26 100
    }
27
28
    /**
29
     * {@inheritdoc}
30
     */
31 56
    protected function loadMetadataFromFile(\ReflectionClass $class, $file)
32
    {
33
        /** @var ClassMetadata $ddrRestClassMetadata */
34 56
        $classMetadata = $this->doctrineDriver->loadMetadataForClass($class);
35 56
        if (null === $classMetadata) {
36
            $classMetadata = new ClassMetadata($class->getName());
37
        }
38
39 56
        $config = Yaml::parse(file_get_contents($file));
40 56
        $className = key($config);
41
42 56
        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 56
        $config = $config[$className];
49 56
        if (!is_array($config)) {
50
            $config = [];
51
        }
52
53 56
        if (array_key_exists('rootResource', $config) && true === $config['rootResource']) {
54 54
            $classMetadata->setRestResource(true);
55
        }
56 56
        if (array_key_exists('service', $config)) {
57 14
            $classMetadata->service = $config['service'];
0 ignored issues
show
Bug introduced by
The property service 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 56
        if (array_key_exists('controller', $config)) {
60
            $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...
61
        }
62 56
        if (array_key_exists('idField', $config)) {
63
            $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...
64
        }
65 56
        if (array_key_exists('pathPrefix', $config)) {
66
            $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...
67
        }
68 56
        if (array_key_exists('namePrefix', $config)) {
69
            $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...
70
        }
71
72 56
        $classMetadata->setMethods($this->parseMethods($config));
73
74 56
        $fieldConfigs = [];
75 56
        if (array_key_exists('fields', $config)) {
76 56
            $fieldConfigs = $config['fields'];
77
        }
78
79 56
        foreach ($class->getProperties() as $reflectionProperty) {
80
81 56
            $propertyName = $reflectionProperty->getName();
82 56
            $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...
83
84 56
            if (array_key_exists($propertyName, $fieldConfigs)) {
85 56
                $fieldConfig = $fieldConfigs[$propertyName];
86 56
                $this->parseFieldConfig($propertyName, $fieldConfig, $propertyMetadata);
87 56
                unset($fieldConfigs[$propertyName]);
88
            }
89
90 56
            $classMetadata->addPropertyMetadata($propertyMetadata);
91
        }
92
93
        /* Parse unbacked field definitions */
94 56
        foreach ($fieldConfigs as $name => $fieldConfig) {
95 34
            $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...
96 34
            $this->parseFieldConfig($name, $fieldConfig, $propertyMetadata);
97 34
            $classMetadata->addPropertyMetadata($propertyMetadata);
98
        }
99
100 56
        return $classMetadata;
101
    }
102
103 56
    protected function parseFieldConfig(string $name, array $fieldConfig, PropertyMetadata $propertyMetadata): void
104
    {
105 56
        $propertyMetadata->setPostable(Postable::parse($fieldConfig['postable'] ?? null));
106 56
        $propertyMetadata->setPuttable(Puttable::parse($fieldConfig['puttable'] ?? null));
107
108 56
        if (null !== $value = $fieldConfig['type'] ?? null) {
109 2
            $propertyMetadata->setType($value);
110
        }
111
112 56
        if (null !== $value = $this->getBool('excluded', $fieldConfig)) {
113 36
            $propertyMetadata->setExcluded($value);
114
        }
115
116 56
        if (null !== $value = $this->getBool('virtual', $fieldConfig)) {
117 32
            $propertyMetadata->setVirtual($value);
118
        }
119
120 56
        if (null !== $subResourceConfig = $fieldConfig['subResource'] ?? null) {
121 52
            $propertyMetadata->setSubResource(true);
122 52
            $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...
123
        }
124
125 56
        if (array_key_exists('includable', $fieldConfig)) {
126 52
            $value = $fieldConfig['includable'];
127 52
            if (is_array($value)) {
128 34
                $propertyMetadata->setIncludable(true);
129 34
                $propertyMetadata->setIncludablePaths($value);
130 52
            } elseif (true === $value) {
131 52
                $propertyMetadata->setIncludable(true);
132 52
                $propertyMetadata->setIncludablePaths([$name]);
133
            }
134
        }
135 56
    }
136
137 56
    private function getBool(string $key, array $haystack, bool $required = false)
138
    {
139 56
        $value = $this->getArrayValue($key, $haystack, $required);
140 56
        if (null === $value) {
141 56
            return null;
142
        }
143
144 36
        if (!is_bool($value)) {
145
            throw new \RuntimeException(sprintf('Value %s must be of type bool', $key));
146
        }
147
148 36
        return $value;
149
    }
150
151 56
    private function getArrayValue(string $key, array $haystack, bool $required = false)
152
    {
153 56
        if (!array_key_exists($key, $haystack)) {
154 56
            if ($required) {
155
                throw new \RuntimeException(sprintf('Value %s is required', $key));
156
            }
157
158 56
            return null;
159
        }
160
161 36
        return $haystack[$key];
162
    }
163
164
    /**
165
     * {@inheritdoc}
166
     */
167 92
    protected function getExtension()
168
    {
169 92
        return 'rest.yml';
170
    }
171
172 56
    protected function getOrCreatePropertymetadata(ClassMetadata $classMetadata, $propertyName): PropertyMetadata
173
    {
174 56
        $propertyMetadata = $classMetadata->getPropertyMetadata($propertyName);
175 56
        if (null === $propertyMetadata) {
176 34
            $propertyMetadata = new PropertyMetadata($classMetadata->name, $propertyName);
177
178 34
            return $propertyMetadata;
179
        }
180
181 54
        return $propertyMetadata;
182
    }
183
184
    /**
185
     * @param array $config
186
     *
187
     * @return Method[]
188
     */
189 56
    private function parseMethods(array $config)
190
    {
191 56
        if (!array_key_exists('methods', $config)) {
192 14
            return null;
193
        }
194
195 54
        $methods = [];
196 54
        $methodsConfig = $config['methods'];
197 54
        foreach ($methodsConfig as $name => $config) {
198 54
            $method = Method::parse($name, $config);
199 54
            $methods[$method->name] = $method;
200
        }
201
202 54
        return $methods;
203
    }
204
}
205