Completed
Push — master ( 126124...e4aaff )
by Dmitry
02:29
created

Annotation   B

Complexity

Total Complexity 49

Size/Duplication

Total Lines 221
Duplicated Lines 7.24 %

Coupling/Cohesion

Components 2
Dependencies 4

Importance

Changes 0
Metric Value
wmc 49
lcom 2
cbo 4
dl 16
loc 221
rs 8.5454
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
C register() 0 31 8
B validateSpace() 0 16 5
F migrate() 6 81 18
A setEntityPostfix() 0 5 1
A setRepositoryPostfix() 0 5 1
A getRepositorySpaceName() 0 4 1
B getSpaceName() 10 23 6
A toUnderscore() 0 12 4
B getTarantoolType() 0 21 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 Annotation 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 Annotation, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Tarantool\Mapper\Plugin;
4
5
use Exception;
6
7
use phpDocumentor\Reflection\DocBlockFactory;
8
use ReflectionClass;
9
use ReflectionProperty;
10
11
use Tarantool\Mapper\Entity;
12
use Tarantool\Mapper\Plugin;
13
use Tarantool\Mapper\Plugin\NestedSet;
14
use Tarantool\Mapper\Repository;
15
16
class Annotation extends UserClasses
17
{
18
    protected $entityClasses = [];
19
    protected $entityPostfix;
20
21
    protected $repositoryClasses = [];
22
    protected $repositoryPostifx;
23
24
    public function register($class)
25
    {
26
        $isEntity = is_subclass_of($class, Entity::class);
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \Tarantool\Mapper\Entity::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
27
        $isRepository = is_subclass_of($class, Repository::class);
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \Tarantool\Mapper\Repository::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
28
29
        if (!$isEntity && !$isRepository) {
30
            throw new Exception("Invalid registration");
31
        }
32
33
        if ($isEntity) {
34
            if ($class == Entity::class) {
35
                throw new Exception("Invalid entity registration");
36
            }
37
            $this->entityClasses[] = $class;
38
        }
39
40
        if ($isRepository) {
41
            if ($class == Repository::class) {
42
                throw new Exception("Invalid repository registration");
43
            }
44
            $this->repositoryClasses[] = $class;
45
        }
46
47
        $space = $this->getSpaceName($class);
48
        if ($isEntity) {
49
            $this->mapEntity($space, $class);
50
        } else {
51
            $this->mapRepository($space, $class);
52
        }
53
        return $this;
54
    }
55
56
    public function validateSpace($space)
57
    {
58
        foreach ($this->entityClasses as $class) {
59
            if ($this->getSpaceName($class) == $space) {
60
                return true;
61
            }
62
        }
63
64
        foreach ($this->repositoryClasses as $class) {
65
            if ($this->getSpaceName($class) == $space) {
66
                return true;
67
            }
68
        }
69
70
        return parent::validateSpace($space);
71
    }
72
73
    public function migrate()
74
    {
75
        $factory = DocBlockFactory::createInstance();
76
77
        $schema = $this->mapper->getSchema();
78
79
        foreach ($this->entityClasses as $entity) {
80
            $spaceName = $this->getSpaceName($entity);
81
            $space = $schema->hasSpace($spaceName) ? $schema->getSpace($spaceName) : $schema->createSpace($spaceName);
82
83
            $this->mapEntity($spaceName, $entity);
84
85
            $class = new ReflectionClass($entity);
86
87
            foreach ($class->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
88
                $description = $factory->create($property->getDocComment());
89
                $tags = $description->getTags('var');
0 ignored issues
show
Unused Code introduced by
The call to DocBlock::getTags() has too many arguments starting with 'var'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
90
91 View Code Duplication
                if (!count($tags)) {
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...
92
                    throw new Exception("No var tag for ".$entity.'::'.$property->getName());
93
                }
94
95 View Code Duplication
                if (count($tags) > 1) {
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...
96
                    throw new Exception("Invalid var tag for ".$entity.'::'.$property->getName());
97
                }
98
99
                $property = $this->toUnderscore($property->getName());
100
                $type = $this->getTarantoolType($tags[0]->getType());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface phpDocumentor\Reflection\DocBlock\Tag as the method getType() does only exist in the following implementations of said interface: phpDocumentor\Reflection\DocBlock\Tags\Param, phpDocumentor\Reflection\DocBlock\Tags\Property, phpDocumentor\Reflection...Block\Tags\PropertyRead, phpDocumentor\Reflection...lock\Tags\PropertyWrite, phpDocumentor\Reflection\DocBlock\Tags\Return_, phpDocumentor\Reflection\DocBlock\Tags\Throws, phpDocumentor\Reflection\DocBlock\Tags\Var_.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
101
102
                if (!$space->hasProperty($property)) {
103
                    $space->addProperty($property, $type);
104
                }
105
            }
106
            if ($this->mapper->hasPlugin(NestedSet::class)) {
107
                $nested = $this->mapper->getPlugin(NestedSet::class);
108
                if ($nested->isNested($space)) {
109
                    $nested->addIndexes($space);
110
                }
111
            }
112
        }
113
114
        foreach ($this->repositoryClasses as $repository) {
115
            $spaceName = $this->getSpaceName($repository);
116
117
            if (!$schema->hasSpace($spaceName)) {
118
                throw new Exception("Repository with no entity definition");
119
            }
120
121
            $this->mapRepository($spaceName, $repository);
122
123
            $space = $schema->getSpace($spaceName);
124
125
            $class = new ReflectionClass($repository);
126
            $properties = $class->getDefaultProperties();
127
128
            if (array_key_exists('indexes', $properties)) {
129
                foreach ($properties['indexes'] as $index) {
0 ignored issues
show
Bug introduced by
The expression $properties['indexes'] of type null|integer|double|string|boolean|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
130
                    if (!is_array($index)) {
131
                        $index = (array) $index;
132
                    }
133
                    if (!array_key_exists('fields', $index)) {
134
                        $index = ['fields' => $index];
135
                    }
136
137
                    $index['if_not_exists'] = true;
138
                    $space->addIndex($index);
139
                }
140
            }
141
        }
142
143
        foreach ($schema->getSpaces() as $space) {
144
            if (!count($space->getIndexes())) {
145
                if (!$space->hasProperty('id')) {
146
                    throw new Exception("No primary index on ". $space->getName());
147
                }
148
                $space->addIndex(['id']);
149
            }
150
        }
151
152
        return $this;
153
    }
154
155
    public function setEntityPostfix($postfix)
156
    {
157
        $this->entityPostfix = $postfix;
158
        return $this;
159
    }
160
161
    public function setRepositoryPostfix($postfix)
162
    {
163
        $this->repositoryPostifx = $postfix;
164
        return $this;
165
    }
166
167
    private $spaceNames = [];
168
169
    public function getRepositorySpaceName($class)
170
    {
171
        return array_search($class, $this->repositoryMapping);
172
    }
173
174
    public function getSpaceName($class)
175
    {
176
        if (!array_key_exists($class, $this->spaceNames)) {
177
            $reflection = new ReflectionClass($class);
178
            $className = $reflection->getShortName();
179
180 View Code Duplication
            if ($reflection->isSubclassOf(Repository::class)) {
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...
181
                if ($this->repositoryPostifx) {
182
                    $className = substr($className, 0, strlen($className) - strlen($this->repositoryPostifx));
183
                }
184
            }
185
186 View Code Duplication
            if ($reflection->isSubclassOf(Entity::class)) {
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
                if ($this->entityPostfix) {
188
                    $className = substr($className, 0, strlen($className) - strlen($this->entityPostfix));
189
                }
190
            }
191
192
            $this->spaceNames[$class] = $this->toUnderscore($className);
193
        }
194
195
        return $this->spaceNames[$class];
196
    }
197
198
    private $underscores = [];
199
200
    private function toUnderscore($input)
201
    {
202
        if (!array_key_exists($input, $this->underscores)) {
203
            preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
204
            $ret = $matches[0];
205
            foreach ($ret as &$match) {
206
                $match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
207
            }
208
            $this->underscores[$input] = implode('_', $ret);
209
        }
210
        return $this->underscores[$input];
211
    }
212
213
    private $tarantoolTypes = [];
214
215
    private function getTarantoolType(string $type)
216
    {
217
        if (array_key_exists($type, $this->tarantoolTypes)) {
218
            return $this->tarantoolTypes[$type];
219
        }
220
221
        if ($type[0] == '\\') {
222
            return $this->tarantoolTypes[$type] = 'unsigned';
223
        }
224
225
        switch ($type) {
226
            case 'array':
227
                return $this->tarantoolTypes[$type] = '*';
228
229
            case 'int':
230
                return $this->tarantoolTypes[$type] = 'unsigned';
231
232
            default:
233
                return $this->tarantoolTypes[$type] = 'str';
234
        }
235
    }
236
}
237