Completed
Push — master ( faed70...56c59d )
by Philip
13:07
created

YamlDriver   A

Complexity

Total Complexity 35

Size/Duplication

Total Lines 187
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 89.36%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 35
lcom 1
cbo 9
dl 0
loc 187
ccs 84
cts 94
cp 0.8936
rs 9
c 1
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
F loadMetadataFromFile() 0 68 14
C parseFieldConfig() 0 33 8
A getBool() 0 13 3
A getArrayValue() 0 12 3
A getExtension() 0 4 1
A getOrCreatePropertymetadata() 0 11 2
A parseMethods() 0 15 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('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 56
        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 56
        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 56
        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 56
        $classMetadata->setMethods($this->parseMethods($config));
70
71 56
        $fieldConfigs = [];
72 56
        if (array_key_exists('fields', $config)) {
73 56
            $fieldConfigs = $config['fields'];
74
        }
75
76 56
        foreach ($class->getProperties() as $reflectionProperty) {
77
78 56
            $propertyName = $reflectionProperty->getName();
79 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...
80
81 56
            if (array_key_exists($propertyName, $fieldConfigs)) {
82 56
                $fieldConfig = $fieldConfigs[$propertyName];
83 56
                $this->parseFieldConfig($propertyName, $fieldConfig, $propertyMetadata);
84 56
                unset($fieldConfigs[$propertyName]);
85
            }
86
87 56
            $classMetadata->addPropertyMetadata($propertyMetadata);
88
        }
89
90
        /* Parse unbacked field definitions */
91 56
        foreach ($fieldConfigs as $name => $fieldConfig) {
92 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...
93 34
            $this->parseFieldConfig($name, $fieldConfig, $propertyMetadata);
94 34
            $classMetadata->addPropertyMetadata($propertyMetadata);
95
        }
96
97 56
        return $classMetadata;
98
    }
99
100 56
    protected function parseFieldConfig(string $name, array $fieldConfig, PropertyMetadata $propertyMetadata): void
101
    {
102 56
        $propertyMetadata->setPostable(Postable::parse($fieldConfig['postable'] ?? null));
103 56
        $propertyMetadata->setPuttable(Puttable::parse($fieldConfig['puttable'] ?? null));
104
105 56
        if (null !== $value = $fieldConfig['type'] ?? null) {
106 2
            $propertyMetadata->setType($value);
107
        }
108
109 56
        if (null !== $value = $this->getBool('excluded', $fieldConfig)) {
110 36
            $propertyMetadata->setExcluded($value);
111
        }
112
113 56
        if (null !== $value = $this->getBool('virtual', $fieldConfig)) {
114 32
            $propertyMetadata->setVirtual($value);
115
        }
116
117 56
        if (null !== $subResourceConfig = $fieldConfig['subResource'] ?? null) {
118 52
            $propertyMetadata->setSubResource(true);
119 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...
120
        }
121
122 56
        if (array_key_exists('includable', $fieldConfig)) {
123 52
            $value = $fieldConfig['includable'];
124 52
            if (is_array($value)) {
125 34
                $propertyMetadata->setIncludable(true);
126 34
                $propertyMetadata->setIncludablePaths($value);
127 52
            } elseif (true === $value) {
128 52
                $propertyMetadata->setIncludable(true);
129 52
                $propertyMetadata->setIncludablePaths([$name]);
130
            }
131
        }
132 56
    }
133
134 56
    private function getBool(string $key, array $haystack, bool $required = false)
135
    {
136 56
        $value = $this->getArrayValue($key, $haystack, $required);
137 56
        if (null === $value) {
138 56
            return null;
139
        }
140
141 36
        if (!is_bool($value)) {
142
            throw new \RuntimeException(sprintf('Value %s must be of type bool', $key));
143
        }
144
145 36
        return $value;
146
    }
147
148 56
    private function getArrayValue(string $key, array $haystack, bool $required = false)
149
    {
150 56
        if (!array_key_exists($key, $haystack)) {
151 56
            if ($required) {
152
                throw new \RuntimeException(sprintf('Value %s is required', $key));
153
            }
154
155 56
            return null;
156
        }
157
158 36
        return $haystack[$key];
159
    }
160
161
    /**
162
     * {@inheritdoc}
163
     */
164 92
    protected function getExtension()
165
    {
166 92
        return 'rest.yml';
167
    }
168
169 56
    protected function getOrCreatePropertymetadata(ClassMetadata $classMetadata, $propertyName): PropertyMetadata
170
    {
171 56
        $propertyMetadata = $classMetadata->getPropertyMetadata($propertyName);
172 56
        if (null === $propertyMetadata) {
173 34
            $propertyMetadata = new PropertyMetadata($classMetadata->name, $propertyName);
174
175 34
            return $propertyMetadata;
176
        }
177
178 54
        return $propertyMetadata;
179
    }
180
181
    /**
182
     * @param array $config
183
     *
184
     * @return Method[]
185
     */
186 56
    private function parseMethods(array $config)
187
    {
188 56
        if (!array_key_exists('methods', $config)) {
189 14
            return null;
190
        }
191
192 54
        $methods = [];
193 54
        $methodsConfig = $config['methods'];
194 54
        foreach ($methodsConfig as $name => $config) {
195 54
            $method = Method::parse($name, $config);
196 54
            $methods[$method->name] = $method;
197
        }
198
199 54
        return $methods;
200
    }
201
}
202