Passed
Pull Request — master (#14)
by Pavel
03:23
created

YmlMetadataDriver   B

Complexity

Total Complexity 50

Size/Duplication

Total Lines 229
Duplicated Lines 11.35 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 78.06%

Importance

Changes 0
Metric Value
wmc 50
lcom 1
cbo 6
dl 26
loc 229
ccs 121
cts 155
cp 0.7806
rs 8.6206
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
F loadMetadataForClass() 0 110 28
C mapAssociation() 26 57 16
A loadMappingFile() 0 4 1
B fieldToArray() 0 27 5

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like YmlMetadataDriver often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use YmlMetadataDriver, and based on these observations, apply Extract Interface, too.

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'] :
82 28
                        EntityMethodProvider::DEFAULT_PATH_SEPARATOR;
83
                $methodProvider =
84 28
                    new EntityMethodProvider($element['client']['entityPath'], $pathSeparator, $methodProvider);
85 28
            }
86
87 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...
88
                throw MappingException::noMethods();
89
            }
90
91 28
            if (null !== $methodProvider) {
92 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...
93 28
            }
94 28
        }
95
96
        // Configure fields
97 28
        if (array_key_exists('fields', $element)) {
98 28
            foreach ($element['fields'] as $field => $mapping) {
99 28
                $mapping = $this->fieldToArray($field, $mapping);
100 28
                $metadata->mapField($mapping);
101 28
            }
102 28
        }
103
104
        // Configure identifiers
105 28
        $associationIds = [];
106 28
        if (array_key_exists('id', $element)) {
107
            // Evaluate identifier settings
108 28
            $defaults = ['generator' => ['strategy' => 'NATURAL']];
109 28
            foreach ($element['id'] as $name => $idElement) {
110 28
                if (isset($idElement['associationKey']) && (bool)$idElement['associationKey'] === true) {
111
                    $associationIds[$name] = true;
112
                    continue;
113
                }
114
115 28
                $mapping = $this->fieldToArray($name, $idElement);
116
117 28
                $mapping['id'] = true;
118 28
                $idElement     = array_replace_recursive($defaults, $idElement);
119
120 28
                $mapping['generator']['strategy'] =
121 28
                    constant(ApiMetadata::class . '::GENERATOR_TYPE_' . $idElement['generator']['strategy']);
122
123 28
                $metadata->mapIdentifier($mapping);
124 28
            }
125 28
        }
126
127 28
        foreach (['oneToOne', 'manyToOne', 'oneToMany', 'manyToMany'] as $type) {
128 28
            if (array_key_exists($type, $element)) {
129 18
                $associations = $element[$type];
130 18
                foreach ($associations as $name => $association) {
131 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...
132 18
                }
133 18
            }
134 28
        }
135 28
    }
136
137
    /**
138
     * @param EntityMetadata $metadata
139
     * @param string         $type
140
     * @param string         $name
141
     * @param array          $association
142
     * @param int[]          $associationIds
143
     */
144 18
    protected function mapAssociation(EntityMetadata $metadata, $type, $name, $association, $associationIds)
145
    {
146 18
        $mapping           = $this->fieldToArray($name, $association);
147 18
        $mapping['target'] = $association['target'];
148 18
        $mapping['sourceEntity'] = $metadata->getName();
149 18
        if (isset($association['fetch'])) {
150
            $mapping['fetch'] = constant(ApiMetadata::class . '::FETCH_' . $association['fetch']);
151
        }
152
        switch ($type) {
153 18
            case 'oneToOne':
154
                $mapping['type'] = EntityMetadata::ONE_TO_ONE;
155
                if (isset($associationIds[$mapping['field']])) {
156
                    $mapping['id'] = true;
157
                }
158
                if (array_key_exists('mappedBy', $association)) {
159
                    $mapping['mappedBy'] = $association['mappedBy'];
160
                }
161
                if (array_key_exists('inversedBy', $association)) {
162
                    $mapping['inversedBy'] = $association['inversedBy'];
163
                }
164
                $metadata->mapOneToOne($mapping);
165
                break;
166 18
            case 'manyToOne':
167 17
                $mapping['type'] = EntityMetadata::MANY_TO_ONE;
168 17
                if (array_key_exists('inversedBy', $association)) {
169 17
                    $mapping['inversedBy'] = $association['inversedBy'];
170 17
                }
171 17
                $metadata->mapManyToOne($mapping);
172 17
                break;
173 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...
174 17
                $mapping['type'] = EntityMetadata::ONE_TO_MANY;
175 17
                if (array_key_exists('mappedBy', $association)) {
176 17
                    $mapping['mappedBy'] = $association['mappedBy'];
177 17
                }
178 17
                if (array_key_exists('orderBy', $association)) {
179
                    $mapping['orderBy'] = $association['orderBy'];
180
                }
181 17
                if (array_key_exists('indexBy', $association)) {
182
                    $mapping['indexBy'] = $association['indexBy'];
183
                }
184 17
                $metadata->mapOneToMany($mapping);
185 17
                break;
186 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...
187 1
                $mapping['type'] = EntityMetadata::MANY_TO_MANY;
188 1
                if (array_key_exists('api_field', $association)) {
189 1
                    $mapping['api_field'] = $association['api_field'];
190 1
                }
191 1
                if (array_key_exists('orderBy', $association)) {
192
                    $mapping['orderBy'] = $association['orderBy'];
193
                }
194 1
                if (array_key_exists('indexBy', $association)) {
195
                    $mapping['indexBy'] = $association['indexBy'];
196
                }
197 1
                $metadata->mapManyToMany($mapping);
198 1
                break;
199
        }
200 18
    }
201
202
    /**
203
     * Loads a mapping file with the given name and returns a map
204
     * from class/entity names to their corresponding file driver elements.
205
     *
206
     * @param string $file The mapping file to load.
207
     *
208
     * @return array
209
     * @throws ParseException
210
     */
211 28
    protected function loadMappingFile($file)
212
    {
213 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...
214
    }
215
216 28
    private function fieldToArray($field, $source)
217
    {
218
        $mapping = [
219 28
            'field'    => $field,
220 28
            'type'     => 'string',
221 28
            'nullable' => true,
222 28
            'options'  => [],
223 28
        ];
224
225 28
        if (array_key_exists('type', $source)) {
226 28
            $mapping['type'] = $source['type'];
227 28
        }
228
229 28
        if (array_key_exists('nullable', $source)) {
230 10
            $mapping['nullable'] = $source['nullable'];
231 10
        }
232
233 28
        if (array_key_exists('api_field', $source)) {
234 26
            $mapping['api_field'] = $source['api_field'];
235 26
        }
236
237 28
        if (array_key_exists('options', $source)) {
238 2
            $mapping['options'] = $source['options'];
239 2
        }
240
241 28
        return $mapping;
242
    }
243
}
244
245