Completed
Push — standalone ( a217df...57a4d8 )
by Philip
02:54
created

YamlDriver::parseFieldConfig()   C

Complexity

Conditions 7
Paths 32

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 8.4953

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 25
ccs 11
cts 16
cp 0.6875
rs 6.7272
cc 7
eloc 15
nc 32
nop 3
crap 8.4953
1
<?php
2
3
namespace Dontdrinkandroot\RestBundle\Metadata\Driver;
4
5
use Dontdrinkandroot\RestBundle\Metadata\ClassMetadata;
6
use Dontdrinkandroot\RestBundle\Metadata\PropertyMetadata;
7
use Metadata\Driver\AbstractFileDriver;
8
use Metadata\Driver\DriverInterface;
9
use Metadata\Driver\FileLocatorInterface;
10
use Symfony\Component\Yaml\Yaml;
11
12
class YamlDriver extends AbstractFileDriver
13
{
14
    /**
15
     * @var DriverInterface
16
     */
17
    private $doctrineDriver;
18
19 38
    public function __construct(FileLocatorInterface $locator, DriverInterface $doctrineDriver)
20
    {
21 38
        parent::__construct($locator);
22 38
        $this->doctrineDriver = $doctrineDriver;
23 38
    }
24
25
    /**
26
     * {@inheritdoc}
27
     */
28 16
    protected function loadMetadataFromFile(\ReflectionClass $class, $file)
29
    {
30
        /** @var ClassMetadata $ddrRestClassMetadata */
31 16
        $classMetadata = $this->doctrineDriver->loadMetadataForClass($class);
32 16
        if (null === $classMetadata) {
33
            $classMetadata = new ClassMetadata($class->getName());
34
        }
35
36 16
        $config = Yaml::parse(file_get_contents($file));
37 16
        $className = key($config);
38
39 16
        if ($className !== $class->name) {
40
            throw new \RuntimeException(
41
                sprintf('Class definition mismatch for "%s" in "%s": %s', $class->getName(), $file, key($config))
42
            );
43
        }
44
45 16
        $config = $config[$className];
46 16
        if (!is_array($config)) {
47
            $config = [];
48
        }
49
50 16
        if (array_key_exists('rootResource', $config) && true === $config['rootResource']) {
51 16
            $classMetadata->setRestResource(true);
52
        }
53
54 16
        if (array_key_exists('service', $config)) {
55 4
            $classMetadata->setService($config['service']);
56
        }
57
58 16
        $fieldConfigs = [];
59 16
        if (array_key_exists('fields', $config)) {
60 16
            $fieldConfigs = $config['fields'];
61
        }
62
63 16
        foreach ($class->getProperties() as $reflectionProperty) {
64
65 16
            $propertyName = $reflectionProperty->getName();
66 16
            $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...
67
68 16
            if (array_key_exists($propertyName, $fieldConfigs)) {
69 16
                $fieldConfig = $fieldConfigs[$propertyName];
70 16
                $this->parseFieldConfig($propertyName, $fieldConfig, $propertyMetadata);
71 16
                unset($fieldConfigs[$propertyName]);
72
            }
73
74 16
            $classMetadata->addPropertyMetadata($propertyMetadata);
75
        }
76
77
        /* Parse unbacked field definitions */
78 16
        foreach ($fieldConfigs as $name => $fieldConfig) {
79 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...
80 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...
81 4
            $classMetadata->addPropertyMetadata($propertyMetadata);
82
        }
83
84 16
        return $classMetadata;
85
    }
86
87 16
    protected function parseFieldConfig(string $name, array $fieldConfig, PropertyMetadata $propertyMetadata): void
88
    {
89 16
        if (null !== $value = $this->getBool('puttable', $fieldConfig)) {
90
            $propertyMetadata->setPuttable($value);
91
        }
92
93 16
        if (null !== $value = $this->getBool('excluded', $fieldConfig)) {
94 4
            $propertyMetadata->setExcluded($value);
95
        }
96
97 16
        if (null !== $value = $this->getBool('postable', $fieldConfig)) {
98
            $propertyMetadata->setPostable($value);
99
        }
100
101 16
        if (array_key_exists('includable', $fieldConfig)) {
102 14
            $value = $fieldConfig['includable'];
103 14
            if (is_array($value)) {
104 14
                $propertyMetadata->setIncludable(true);
105 14
                $propertyMetadata->setIncludablePaths($value);
106
            } elseif (true === $value) {
107
                $propertyMetadata->setIncludable(true);
108
                $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...
109
            }
110
        }
111 16
    }
112
113 16
    private function getBool(string $key, array $haystack, bool $required = false)
114
    {
115 16
        if (!array_key_exists($key, $haystack)) {
116 16
            if ($required) {
117
                throw new \RuntimeException(sprintf('Value %s is required', $key));
118
            }
119
120 16
            return null;
121
        }
122
123 4
        $value = $haystack[$key];
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
    /**
132
     * {@inheritdoc}
133
     */
134 38
    protected function getExtension()
135
    {
136 38
        return 'rest.yml';
137
    }
138
139 16
    protected function getOrCreatePropertymetadata(ClassMetadata $classMetadata, $propertyName): PropertyMetadata
140
    {
141 16
        $propertyMetadata = $classMetadata->getPropertyMetadata($propertyName);
142 16
        if (null === $propertyMetadata) {
143 4
            $propertyMetadata = new PropertyMetadata($classMetadata->name, $propertyName);
144
145 4
            return $propertyMetadata;
146
        }
147
148 14
        return $propertyMetadata;
149
    }
150
}
151