Completed
Push — master ( 4aff6e...f50da1 )
by Dmitry
02:26
created

Annotation::validateSpace()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 8
nc 7
nop 1
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\Repository;
14
15
class Annotation extends UserClasses
16
{
17
    protected $entityClasses = [];
18
    protected $entityPostfix;
19
20
    protected $repositoryClasses = [];
21
    protected $repositoryPostifx;
22
23
    public function register($class)
24
    {
25
        $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...
26
        $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...
27
28
        if (!$isEntity && !$isRepository) {
29
            throw new Exception("Invalid registration");
30
        }
31
32
        if ($isEntity) {
33
            if ($class == Entity::class) {
34
                throw new Exception("Invalid entity registration");
35
            }
36
            $this->entityClasses[] = $class;
37
        }
38
39
        if ($isRepository) {
40
            if ($class == Repository::class) {
41
                throw new Exception("Invalid repository registration");
42
            }
43
            $this->repositoryClasses[] = $class;
44
        }
45
46
        $space = $this->getSpaceName($class);
47
        if ($isEntity) {
48
            $this->mapEntity($space, $class);
49
        } else {
50
            $this->mapRepository($space, $class);
51
        }
52
        return $this;
53
    }
54
55
    public function validateSpace($space)
56
    {
57
        foreach($this->entityClasses as $class) {
58
            if($this->getSpaceName($class) == $space) {
59
                return true;
60
            }
61
        }
62
63
        foreach($this->repositoryClasses as $class) {
64
            if($this->getSpaceName($class) == $space) {
65
                return true;
66
            }
67
        }
68
69
        return parent::validateSpace($space);
70
    }
71
72
    public function migrate()
73
    {
74
        $factory = DocBlockFactory::createInstance();
75
76
        $schema = $this->mapper->getSchema();
77
78
        foreach ($this->entityClasses as $entity) {
79
            $spaceName = $this->getSpaceName($entity);
80
            $space = $schema->hasSpace($spaceName) ? $schema->getSpace($spaceName) : $schema->createSpace($spaceName);
81
82
            $this->mapEntity($spaceName, $entity);
83
84
            $class = new ReflectionClass($entity);
85
86
            foreach ($class->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
87
                $description = $factory->create($property->getDocComment());
88
                $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...
89
90 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...
91
                    throw new Exception("No var tag for ".$entity.'::'.$property->getName());
92
                }
93
94 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...
95
                    throw new Exception("Invalid var tag for ".$entity.'::'.$property->getName());
96
                }
97
98
                $property = $this->toUnderscore($property->getName());
99
                $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...
100
101
                if (!$space->hasProperty($property)) {
102
                    $space->addProperty($property, $type);
103
                }
104
            }
105
        }
106
107
        foreach ($this->repositoryClasses as $repository) {
108
            $spaceName = $this->getSpaceName($repository);
109
110
            if (!$schema->hasSpace($spaceName)) {
111
                throw new Exception("Repository with no entity definition");
112
            }
113
114
            $this->mapRepository($spaceName, $repository);
115
116
            $space = $schema->getSpace($spaceName);
117
118
            $class = new ReflectionClass($repository);
119
            $properties = $class->getDefaultProperties();
120
121
            if (array_key_exists('indexes', $properties)) {
122
                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...
123
                    if (!is_array($index)) {
124
                        $index = (array) $index;
125
                    }
126
                    if (!array_key_exists('fields', $index)) {
127
                        $index = ['fields' => $index];
128
                    }
129
130
                    $index['if_not_exists'] = true;
131
                    $space->addIndex($index);
132
                }
133
            }
134
        }
135
136
        foreach ($schema->getSpaces() as $space) {
137
            if (!count($space->getIndexes())) {
138
                if (!$space->hasProperty('id')) {
139
                    throw new Exception("No primary index on ". $space->getName());
140
                }
141
                $space->addIndex(['id']);
142
            }
143
        }
144
145
        return $this;
146
    }
147
148
    public function setEntityPostfix($postfix)
149
    {
150
        $this->entityPostfix = $postfix;
151
        return $this;
152
    }
153
154
    public function setRepositoryPostfix($postfix)
155
    {
156
        $this->repositoryPostifx = $postfix;
157
        return $this;
158
    }
159
160
    private $spaceNames = [];
161
162
    public function getRepositorySpaceName($class)
163
    {
164
        return array_search($class, $this->repositoryMapping);
165
    }
166
167
    public function getSpaceName($class)
168
    {
169
        if (!array_key_exists($class, $this->spaceNames)) {
170
            $reflection = new ReflectionClass($class);
171
            $className = $reflection->getShortName();
172
173 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...
174
                if ($this->repositoryPostifx) {
175
                    $className = substr($className, 0, strlen($className) - strlen($this->repositoryPostifx));
176
                }
177
            }
178
179 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...
180
                if ($this->entityPostfix) {
181
                    $className = substr($className, 0, strlen($className) - strlen($this->entityPostfix));
182
                }
183
            }
184
185
            $this->spaceNames[$class] = $this->toUnderscore($className);
186
        }
187
188
        return $this->spaceNames[$class];
189
    }
190
191
    private $underscores = [];
192
193
    private function toUnderscore($input)
194
    {
195
        if (!array_key_exists($input, $this->underscores)) {
196
            preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
197
            $ret = $matches[0];
198
            foreach ($ret as &$match) {
199
                $match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
200
            }
201
            $this->underscores[$input] = implode('_', $ret);
202
        }
203
        return $this->underscores[$input];
204
    }
205
206
    private $tarantoolTypes = [];
207
208
    private function getTarantoolType(string $type)
209
    {
210
        if (array_key_exists($type, $this->tarantoolTypes)) {
211
            return $this->tarantoolTypes[$type];
212
        }
213
214
        if ($type[0] == '\\') {
215
            return $this->tarantoolTypes[$type] = 'unsigned';
216
        }
217
218
        switch ($type) {
219
            case 'int':
220
                return $this->tarantoolTypes[$type] = 'unsigned';
221
222
            default:
223
                return $this->tarantoolTypes[$type] = 'str';
224
        }
225
    }
226
}
227