Completed
Push — standalone ( fce7e0...46923f )
by Philip
03:02
created

YamlDriver::parseMethods()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6.0106

Importance

Changes 0
Metric Value
dl 0
loc 24
ccs 14
cts 15
cp 0.9333
rs 8.5125
c 0
b 0
f 0
cc 6
eloc 15
nc 7
nop 1
crap 6.0106
1
<?php
2
3
namespace Dontdrinkandroot\RestBundle\Metadata\Driver;
4
5
use Dontdrinkandroot\RestBundle\Metadata\Annotation\Method;
6
use Dontdrinkandroot\RestBundle\Metadata\Annotation\Right;
7
use Dontdrinkandroot\RestBundle\Metadata\ClassMetadata;
8
use Dontdrinkandroot\RestBundle\Metadata\PropertyMetadata;
9
use Metadata\Driver\AbstractFileDriver;
10
use Metadata\Driver\DriverInterface;
11
use Metadata\Driver\FileLocatorInterface;
12
use Symfony\Component\Yaml\Yaml;
13
14
class YamlDriver extends AbstractFileDriver
15
{
16
    /**
17
     * @var DriverInterface
18
     */
19
    private $doctrineDriver;
20
21 38
    public function __construct(FileLocatorInterface $locator, DriverInterface $doctrineDriver)
22
    {
23 38
        parent::__construct($locator);
24 38
        $this->doctrineDriver = $doctrineDriver;
25 38
    }
26
27
    /**
28
     * {@inheritdoc}
29
     */
30 22
    protected function loadMetadataFromFile(\ReflectionClass $class, $file)
31
    {
32
        /** @var ClassMetadata $ddrRestClassMetadata */
33 22
        $classMetadata = $this->doctrineDriver->loadMetadataForClass($class);
34 22
        if (null === $classMetadata) {
35
            $classMetadata = new ClassMetadata($class->getName());
36
        }
37
38 22
        $config = Yaml::parse(file_get_contents($file));
39 22
        $className = key($config);
40
41 22
        if ($className !== $class->name) {
42
            throw new \RuntimeException(
43
                sprintf('Class definition mismatch for "%s" in "%s": %s', $class->getName(), $file, key($config))
44
            );
45
        }
46
47 22
        $config = $config[$className];
48 22
        if (!is_array($config)) {
49
            $config = [];
50
        }
51
52 22
        if (array_key_exists('rootResource', $config) && true === $config['rootResource']) {
53 22
            $classMetadata->setRestResource(true);
54
        }
55
56 22
        $classMetadata->service = $config['service'] ?? null;
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...
57 22
        $classMetadata->idField = $config['idField'] ?? null;
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...
58
59 22
        $classMetadata->setMethods($this->parseMethods($config));
60
61 22
        $fieldConfigs = [];
62 22
        if (array_key_exists('fields', $config)) {
63 22
            $fieldConfigs = $config['fields'];
64
        }
65
66 22
        foreach ($class->getProperties() as $reflectionProperty) {
67
68 22
            $propertyName = $reflectionProperty->getName();
69 22
            $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...
70
71 22
            if (array_key_exists($propertyName, $fieldConfigs)) {
72 22
                $fieldConfig = $fieldConfigs[$propertyName];
73 22
                $this->parseFieldConfig($propertyName, $fieldConfig, $propertyMetadata);
74 22
                unset($fieldConfigs[$propertyName]);
75
            }
76
77 22
            $classMetadata->addPropertyMetadata($propertyMetadata);
78
        }
79
80
        /* Parse unbacked field definitions */
81 22
        foreach ($fieldConfigs as $name => $fieldConfig) {
82 6
            $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...
83 6
            $this->parseFieldConfig($name, $fieldConfig, $propertyMetadata);
84 6
            $classMetadata->addPropertyMetadata($propertyMetadata);
85
        }
86
87 22
        return $classMetadata;
88
    }
89
90 22
    protected function parseFieldConfig(string $name, array $fieldConfig, PropertyMetadata $propertyMetadata): void
91
    {
92 22
        if (null !== $value = $this->getBool('postable', $fieldConfig)) {
93
            $propertyMetadata->setPostable($value);
94
        }
95
96 22
        if (null !== $value = $this->getBool('puttable', $fieldConfig)) {
97
            $propertyMetadata->setPuttable($value);
98
        }
99
100 22
        if (null !== $value = $this->getBool('excluded', $fieldConfig)) {
101 6
            $propertyMetadata->setExcluded($value);
102
        }
103
104 22
        if (null !== $subResourceConfig = $fieldConfig['subResource'] ?? null) {
105 20
            $propertyMetadata->setSubResource(true);
106 20
            $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...
107
        }
108
109 22
        if (array_key_exists('includable', $fieldConfig)) {
110 20
            $value = $fieldConfig['includable'];
111 20
            if (is_array($value)) {
112 20
                $propertyMetadata->setIncludable(true);
113 20
                $propertyMetadata->setIncludablePaths($value);
114
            } elseif (true === $value) {
115
                $propertyMetadata->setIncludable(true);
116
                $propertyMetadata->setIncludablePaths([$name]);
0 ignored issues
show
Documentation introduced by
array($name) is of type array<integer,string,{"0":"string"}>, but the function expects a null|array<integer,object<string>>.

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...
117
            }
118
        }
119 22
    }
120
121 22
    private function getBool(string $key, array $haystack, bool $required = false)
122
    {
123 22
        $value = $this->getArrayValue($key, $haystack, $required);
124 22
        if (null === $value) {
125 22
            return null;
126
        }
127
128 6
        if (!is_bool($value)) {
129
            throw new \RuntimeException(sprintf('Value %s must be of type bool', $key));
130
        }
131
132 6
        return $value;
133
    }
134
135 22
    private function getArrayValue(string $key, array $haystack, bool $required = false)
136
    {
137 22
        if (!array_key_exists($key, $haystack)) {
138 22
            if ($required) {
139
                throw new \RuntimeException(sprintf('Value %s is required', $key));
140
            }
141
142 22
            return null;
143
        }
144
145 22
        return $haystack[$key];
146
    }
147
148
    /**
149
     * {@inheritdoc}
150
     */
151 38
    protected function getExtension()
152
    {
153 38
        return 'rest.yml';
154
    }
155
156 22
    protected function getOrCreatePropertymetadata(ClassMetadata $classMetadata, $propertyName): PropertyMetadata
157
    {
158 22
        $propertyMetadata = $classMetadata->getPropertyMetadata($propertyName);
159 22
        if (null === $propertyMetadata) {
160 6
            $propertyMetadata = new PropertyMetadata($classMetadata->name, $propertyName);
161
162 6
            return $propertyMetadata;
163
        }
164
165 20
        return $propertyMetadata;
166
    }
167
168
    /**
169
     * @param array $config
170
     *
171
     * @return Method[]
172
     */
173 22
    private function parseMethods(array $config)
174
    {
175 22
        if (!array_key_exists('methods', $config)) {
176
            return null;
177
        }
178
179 22
        $methods = [];
180 22
        $methodsConfig = $config['methods'];
181 22
        foreach ($methodsConfig as $name => $config) {
182 22
            $method = new Method();
183 22
            $method->name = $name;
0 ignored issues
show
Documentation Bug introduced by
It seems like $name can also be of type integer. However, the property $name is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
184 22
            if (null !== $config) {
185 20
                if (array_key_exists('right', $config)) {
186 20
                    $method->right = $this->parseRight($config['right']);
187
                }
188 20
                if (array_key_exists('defaultIncludes', $config)) {
189 20
                    $method->defaultIncludes = $config['defaultIncludes'];
190
                }
191
            }
192 22
            $methods[$method->name] = $method;
193
        }
194
195 22
        return $methods;
196
    }
197
198 20
    private function parseRight(array $config): Right
199
    {
200 20
        $right = new Right();
201 20
        $right->attributes = $this->getArrayValue('attributes', $config);
202 20
        $right->propertyPath = $this->getArrayValue('propertyPath', $config);
203
204 20
        return $right;
205
    }
206
}
207