Passed
Push — master ( b9799d...bbe0a2 )
by Pavel
04:02
created

YmlMetadataDriver::fieldToArray()   B

Complexity

Conditions 5
Paths 16

Size

Total Lines 27
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 27
c 0
b 0
f 0
ccs 19
cts 19
cp 1
rs 8.439
cc 5
eloc 15
nc 16
nop 2
crap 5
1
<?php
2
3
namespace Bankiru\Api\Doctrine\Mapping\Driver;
4
5
use Bankiru\Api\Doctrine\Exception\MappingException;
6
use Bankiru\Api\Doctrine\Mapping\ApiMetadata;
7
use Bankiru\Api\Doctrine\Mapping\EntityMetadata;
8
use Bankiru\Api\Doctrine\Rpc\Method\EntityMethodProvider;
9
use Bankiru\Api\Doctrine\Rpc\Method\MethodProvider;
10
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
11
use Doctrine\Common\Persistence\Mapping\Driver\FileDriver;
12
use Symfony\Component\Yaml\Exception\ParseException;
13
use Symfony\Component\Yaml\Yaml;
14
15
class YmlMetadataDriver extends FileDriver
16
{
17
    /**
18
     * Loads the metadata for the specified class into the provided container.
19
     *
20
     * @param string                       $className
21
     * @param EntityMetadata|ClassMetadata $metadata
22
     *
23
     * @return void
24
     * @throws MappingException
25
     */
26 28
    public function loadMetadataForClass($className, ClassMetadata $metadata)
27
    {
28 28
        $element = $this->getElement($className);
29
30 28
        switch ($element['type']) {
31 28
            case 'entity':
32 28
                if (array_key_exists('repositoryClass', $element)) {
33 2
                    $metadata->setCustomRepositoryClass($element['repositoryClass']);
34 2
                }
35 28
                break;
36
            case 'mappedSuperclass':
37
                $metadata->isMappedSuperclass = true;
0 ignored issues
show
Bug introduced by
Accessing isMappedSuperclass on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
38
                $metadata->setCustomRepositoryClass(
39
                    array_key_exists('repositoryClass', $element) ? $element['repositoryClass'] : null
40
                );
41
                break;
42 28
        }
43
44
        // Configure API
45 28
        if (array_key_exists('api', $element)) {
46 28
            if (array_key_exists('factory', $element['api'])) {
47 28
                $metadata->apiFactory = $element['api']['factory'];
0 ignored issues
show
Bug introduced by
Accessing apiFactory on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
48 28
            }
49 28
        }
50
51
        // Evaluate discriminatorColumn
52 28
        if (isset($element['discriminatorField'])) {
53 4
            $discrColumn = $element['discriminatorField'];
54 4
            $metadata->setDiscriminatorField(
55
                [
56 4
                    'name' => isset($discrColumn['name']) ? (string)$discrColumn['name'] : null,
57 4
                    'type' => isset($discrColumn['type']) ? (string)$discrColumn['type'] : 'string',
58
                ]
59 4
            );
60 4
        } else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
61
            // $metadata->setDiscriminatorField(['name' => 'dtype', 'type' => 'string']);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
62
        }
63
        // Evaluate discriminatorMap
64 28
        if (isset($element['discriminatorMap'])) {
65
            $metadata->setDiscriminatorMap($element['discriminatorMap']);
66
        }
67
68
        // Configure Client
69 28
        if (array_key_exists('client', $element)) {
70 28
            if (array_key_exists('name', $element['client'])) {
71 28
                $metadata->clientName = $element['client']['name'];
0 ignored issues
show
Bug introduced by
Accessing clientName on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
72 28
            }
73
74 28
            $methodProvider = null;
75 28
            if (array_key_exists('methods', $element['client'])) {
76
                $methodProvider = new MethodProvider($element['client']['methods']);
77 1
            }
78 28
            if (array_key_exists('entityPath', $element['client'])) {
79
                $pathSeparator  =
80 28
                    array_key_exists('entityPathSeparator', $element['client']) ?
81 28
                        $element['client']['entityPathSeparator'] : EntityMethodProvider::DEFAULT_PATH_SEPARATOR;
82
                $methodProvider =
83 28
                    new EntityMethodProvider($element['client']['entityPath'], $pathSeparator, $methodProvider);
84 28
            }
85
86 28
            if (null === $methodProvider && null === $metadata->methodProvider) {
0 ignored issues
show
Bug introduced by
Accessing methodProvider on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
87
                throw MappingException::noMethods();
88
            }
89
90 28
            if (null !== $methodProvider) {
91 28
                $metadata->methodProvider = $methodProvider;
0 ignored issues
show
Bug introduced by
Accessing methodProvider on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
92 28
            }
93 28
        }
94
95
        // Configure fields
96 28
        if (array_key_exists('fields', $element)) {
97 28
            foreach ($element['fields'] as $field => $mapping) {
98 28
                $mapping = $this->fieldToArray($field, $mapping);
99 28
                $metadata->mapField($mapping);
100 28
            }
101 28
        }
102
103
        // Configure identifiers
104 28
        $associationIds = [];
105 28
        if (array_key_exists('id', $element)) {
106
            // Evaluate identifier settings
107 28
            $defaults = ['generator' => ['strategy' => 'NATURAL']];
108 28
            foreach ($element['id'] as $name => $idElement) {
109 28
                if (isset($idElement['associationKey']) && (bool)$idElement['associationKey'] === true) {
110
                    $associationIds[$name] = true;
111
                    continue;
112
                }
113
114 28
                $mapping = $this->fieldToArray($name, $idElement);
115
116 28
                $mapping['id'] = true;
117 28
                $idElement     = array_replace_recursive($defaults, $idElement);
118
119 28
                $mapping['generator']['strategy'] =
120 28
                    constant(ApiMetadata::class . '::GENERATOR_TYPE_' . $idElement['generator']['strategy']);
121
122 28
                $metadata->mapIdentifier($mapping);
123 28
            }
124 28
        }
125
126 28
        foreach (['oneToOne', 'manyToOne', 'oneToMany', 'manyToMany'] as $type) {
127 28
            if (array_key_exists($type, $element)) {
128 18
                $associations = $element[$type];
129 18
                foreach ($associations as $name => $association) {
130 18
                    $this->mapAssociation($metadata, $type, $name, $association, $associationIds);
0 ignored issues
show
Compatibility introduced by
$metadata of type object<Doctrine\Common\P...\Mapping\ClassMetadata> is not a sub-type of object<Bankiru\Api\Doctr...Mapping\EntityMetadata>. It seems like you assume a concrete implementation of the interface Doctrine\Common\Persistence\Mapping\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...
131 18
                }
132 18
            }
133 28
        }
134 28
    }
135
136
    /**
137
     * @param EntityMetadata $metadata
138
     * @param string         $type
139
     * @param string         $name
140
     * @param array          $association
141
     * @param int[]          $associationIds
142
     */
143 18
    protected function mapAssociation(EntityMetadata $metadata, $type, $name, $association, $associationIds)
144
    {
145 18
        $mapping = $this->fieldToArray($name, $association);
146 18
        $mapping['targetEntity'] = $association['targetEntity'];
147 18
        $mapping['sourceEntity'] = $metadata->getName();
148 18
        if (isset($association['fetch'])) {
149
            $mapping['fetch'] = constant(ApiMetadata::class . '::FETCH_' . $association['fetch']);
150
        }
151
        switch ($type) {
152 18
            case 'oneToOne':
153
                $mapping['type'] = EntityMetadata::ONE_TO_ONE;
154
                if (isset($associationIds[$mapping['field']])) {
155
                    $mapping['id'] = true;
156
                }
157
                if (array_key_exists('mappedBy', $association)) {
158
                    $mapping['mappedBy'] = $association['mappedBy'];
159
                }
160
                if (array_key_exists('inversedBy', $association)) {
161
                    $mapping['inversedBy'] = $association['inversedBy'];
162
                }
163
                $metadata->mapOneToOne($mapping);
164
                break;
165 18
            case 'manyToOne':
166 17
                $mapping['type'] = EntityMetadata::MANY_TO_ONE;
167 17
                if (array_key_exists('inversedBy', $association)) {
168 17
                    $mapping['inversedBy'] = $association['inversedBy'];
169 17
                }
170 17
                $metadata->mapManyToOne($mapping);
171 17
                break;
172 18 View Code Duplication
            case 'oneToMany':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
173 17
                $mapping['type'] = EntityMetadata::ONE_TO_MANY;
174 17
                if (array_key_exists('mappedBy', $association)) {
175 17
                    $mapping['mappedBy'] = $association['mappedBy'];
176 17
                }
177 17
                if (array_key_exists('orderBy', $association)) {
178
                    $mapping['orderBy'] = $association['orderBy'];
179
                }
180 17
                if (array_key_exists('indexBy', $association)) {
181
                    $mapping['indexBy'] = $association['indexBy'];
182
                }
183 17
                $metadata->mapOneToMany($mapping);
184 17
                break;
185 1 View Code Duplication
            case 'manyToMany':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
186 1
                $mapping['type'] = EntityMetadata::MANY_TO_MANY;
187 1
                if (array_key_exists('apiField', $association)) {
188 1
                    $mapping['apiField'] = $association['apiField'];
189 1
                }
190 1
                if (array_key_exists('orderBy', $association)) {
191
                    $mapping['orderBy'] = $association['orderBy'];
192
                }
193 1
                if (array_key_exists('indexBy', $association)) {
194
                    $mapping['indexBy'] = $association['indexBy'];
195
                }
196 1
                $metadata->mapManyToMany($mapping);
197 1
                break;
198
        }
199 18
    }
200
201
    /**
202
     * Loads a mapping file with the given name and returns a map
203
     * from class/entity names to their corresponding file driver elements.
204
     *
205
     * @param string $file The mapping file to load.
206
     *
207
     * @return array
208
     * @throws ParseException
209
     */
210 28
    protected function loadMappingFile($file)
211
    {
212 28
        return Yaml::parse(file_get_contents($file));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return \Symfony\Componen...e_get_contents($file)); (string|array|stdClass) is incompatible with the return type declared by the abstract method Doctrine\Common\Persiste...Driver::loadMappingFile of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
213
    }
214
215 28
    private function fieldToArray($field, $source)
216
    {
217
        $mapping = [
218 28
            'field'    => $field,
219 28
            'type'     => 'string',
220 28
            'nullable' => true,
221 28
            'options'  => [],
222 28
        ];
223
224 28
        if (array_key_exists('type', $source)) {
225 28
            $mapping['type'] = $source['type'];
226 28
        }
227
228 28
        if (array_key_exists('nullable', $source)) {
229 10
            $mapping['nullable'] = $source['nullable'];
230 10
        }
231
232 28
        if (array_key_exists('apiField', $source)) {
233 26
            $mapping['apiField'] = $source['apiField'];
234 26
        }
235
236 28
        if (array_key_exists('options', $source)) {
237 2
            $mapping['options'] = $source['options'];
238 2
        }
239
240 28
        return $mapping;
241
    }
242
}
243
244