Completed
Push — standalone ( 787e4c...e35bae )
by Philip
07:04
created

YamlDriver::parseMethods()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5.0187

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 10
cts 11
cp 0.9091
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 11
nc 4
nop 1
crap 5.0187
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($propertyName, $fieldConfig, $propertyMetadata);
0 ignored issues
show
Bug introduced by
The variable $propertyName does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
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 = Method::create($name);
179 18
            if (null !== $config && array_key_exists('right', $config)) {
180 16
                $method->right = $this->parseRight($config['right']);
181
            }
182 18
            $methods[$method->getName()] = $method;
183
        }
184
185 18
        return $methods;
186
    }
187
188 16
    private function parseRight(array $config): Right
189
    {
190 16
        $right = new Right();
191 16
        $right->attributes = $this->getArrayValue('attributes', $config);
192 16
        $right->propertyPath = $this->getArrayValue('propertyPath', $config);
193
194 16
        return $right;
195
    }
196
}
197