Completed
Push — standalone ( 444422...a45559 )
by Philip
05:18
created

YamlDriver::parseRight()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

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