Completed
Push — master ( 654356...b90ebf )
by Dmitry
02:31
created

DocBlock   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 138
Duplicated Lines 4.35 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 30
lcom 1
cbo 4
dl 6
loc 138
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
D register() 0 33 9
C migrate() 6 66 14
A toUnderscore() 0 12 4
A getTarantoolType() 0 14 3

How to fix   Duplicated Code   

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:

1
<?php
2
3
namespace Tarantool\Mapper\Plugins;
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\Repository;
14
15
class DocBlock extends UserClasses
16
{
17
    private $entities = [];
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
18
    private $repositories = [];
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
19
20
    public function register($class)
21
    {
22
        $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...
23
        $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...
24
25
        if(!$isEntity && !$isRepository) {
26
            throw new Exception("Invalid registration");
27
        }
28
29
        if($isEntity) {
30
            if($class == Entity::class) {
31
                throw new Exception("Invalid entity registration");
32
            }
33
            $this->entities[] = $class;
34
        }
35
36
        if($isRepository) {
37
            if($class == Repository::class) {
38
                throw new Exception("Invalid repository registration");
39
            }
40
            $this->repositories[] = $class;
41
        }
42
43
        $reflection = new ReflectionClass($class);
44
        $space = $this->toUnderscore($reflection->getShortName());
45
        if($this->mapper->getSchema()->hasSpace($space)) {
46
            if($isEntity) {
47
                $this->mapEntity($name, $class);
0 ignored issues
show
Bug introduced by
The variable $name does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
48
            } else {
49
                $this->mapRepository($name, $class);
50
            }
51
        }
52
    }
53
54
    public function migrate()
55
    {
56
        $factory = DocBlockFactory::createInstance();
57
58
        $schema = $this->mapper->getSchema();
59
60
        foreach($this->entities as $entity) {
61
62
            $class = new ReflectionClass($entity);
63
            $spaceName = $this->toUnderscore($class->getShortName());
64
65
            $space = $schema->hasSpace($spaceName) ? $schema->getSpace($spaceName) : $schema->createSpace($spaceName);
66
            $this->mapEntity($spaceName, $entity);
67
68
            foreach($class->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
69
70
                $description = $factory->create($property->getDocComment());
71
                $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...
72
73 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...
74
                    throw new Exception("No var tag for ".$entity.'::'.$property->getName());
75
                }
76
77 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...
78
                    throw new Exception("Invalid var tag for ".$entity.'::'.$property->getName());
79
                }
80
81
                $property = $this->toUnderscore($property->getName());
82
                $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...
83
84
                if(!$space->hasProperty($property)) {
85
                    $space->addProperty($property, $type);
86
                }
87
            }
88
        }
89
90
        foreach($this->repositories as $repository) {
91
92
            $class = new ReflectionClass($repository);
93
            $spaceName = $this->toUnderscore($class->getShortName());
94
95
            if(!$schema->hasSpace($spaceName)) {
96
                throw new Exception("Repository with no entity definition");
97
            }
98
99
            $this->mapRepository($spaceName, $repository);
100
101
            $space = $schema->getSpace($spaceName);
102
            $properties = $class->getDefaultProperties();
103
            if(array_key_exists('indexes', $properties)) {
104
                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...
105
                    $space->addIndex($index);
106
                }
107
            }
108
        }
109
110
        foreach($schema->getSpaces() as $space) {
111
112
            if(!count($space->getIndexes())) {
113
                if(!$space->hasProperty('id')) {
114
                    throw new Exception("No primary index on ". $space->getName());
115
                }
116
                $space->addIndex(['id']);
117
            }
118
        }
119
    }
120
121
    private $underscores = [];
122
123
    private function toUnderscore($input)
124
    {
125
        if(!array_key_exists($input, $this->underscores)) {
126
            preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
127
            $ret = $matches[0];
128
            foreach ($ret as &$match) {
129
                $match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
130
            }
131
            $this->underscores[$input] = implode('_', $ret);
132
        }
133
        return $this->underscores[$input];
134
    }
135
136
    private $tarantoolTypes = [];
137
138
    private function getTarantoolType(string $type)
139
    {
140
        if(array_key_exists($type, $this->tarantoolTypes)) {
141
            return $this->tarantoolTypes[$type];
142
        }
143
144
        switch($type) {
145
            case 'int':
146
                return $this->tarantoolTypes[$type] = 'unsigned';
147
148
            default:
149
                return $this->tarantoolTypes[$type] = 'str';
150
        }
151
    }
152
}
153