Completed
Push — master ( 12fe6d...b436a3 )
by Dmitry
01:45
created

Annotation::isReference()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Tarantool\Mapper\Plugin;
4
5
use Exception;
6
7
use phpDocumentor\Reflection\DocBlockFactory;
8
use phpDocumentor\Reflection\Types\ContextFactory;
9
use ReflectionClass;
10
use ReflectionProperty;
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
        $contextFactory = new ContextFactory();
77
78
        $schema = $this->mapper->getSchema();
79
80
        foreach ($this->entityClasses as $entity) {
81
            $spaceName = $this->getSpaceName($entity);
82
            $space = $schema->hasSpace($spaceName) ? $schema->getSpace($spaceName) : $schema->createSpace($spaceName);
83
84
            $this->mapEntity($spaceName, $entity);
85
86
            $class = new ReflectionClass($entity);
87
88
            foreach ($class->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
89
                $context = $contextFactory->createFromReflector($property);
90
                $description = $factory->create($property->getDocComment(), $context);
91
                $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...
92
93 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...
94
                    throw new Exception("No var tag for ".$entity.'::'.$property->getName());
95
                }
96
97 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...
98
                    throw new Exception("Invalid var tag for ".$entity.'::'.$property->getName());
99
                }
100
101
                $propertyName = $this->toUnderscore($property->getName());
102
                $phpType = $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...
103
                $type = $this->getTarantoolType($phpType);
104
105
                if (!$space->hasProperty($propertyName)) {
106
                    if ($this->isReference($phpType)) {
107
                        $space->addProperty($propertyName, $type, $this->getSpaceName((string) $phpType));
108
                    } else {
109
                        $space->addProperty($propertyName, $type);
110
                    }
111
                }
112
            }
113
            if ($this->mapper->hasPlugin(NestedSet::class)) {
114
                $nested = $this->mapper->getPlugin(NestedSet::class);
115
                if ($nested->isNested($space)) {
116
                    $nested->addIndexes($space);
117
                }
118
            }
119
        }
120
121
        foreach ($this->repositoryClasses as $repository) {
122
            $spaceName = $this->getSpaceName($repository);
123
124
            if (!$schema->hasSpace($spaceName)) {
125
                throw new Exception("Repository with no entity definition");
126
            }
127
128
            $this->mapRepository($spaceName, $repository);
129
130
            $space = $schema->getSpace($spaceName);
131
132
            $class = new ReflectionClass($repository);
133
            $properties = $class->getDefaultProperties();
134
135
            if (array_key_exists('indexes', $properties)) {
136
                foreach ($properties['indexes'] as $i => $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...
137
                    if (!is_array($index)) {
138
                        $index = (array) $index;
139
                    }
140
                    if (!array_key_exists('fields', $index)) {
141
                        $index = ['fields' => $index];
142
                    }
143
144
                    $index['if_not_exists'] = true;
145
                    try {
146
                        $space->addIndex($index);
147
                    } catch (Exception $e) {
148
                        $presentation = json_encode($properties['indexes'][$i]);
149
                        throw new Exception("Failed to add index $presentation. ". $e->getMessage(), 0, $e);
150
                    }
151
                }
152
            }
153
        }
154
155
        foreach ($schema->getSpaces() as $space) {
156
            if (!count($space->getIndexes())) {
157
                if (!$space->hasProperty('id')) {
158
                    throw new Exception("No primary index on ". $space->getName());
159
                }
160
                $space->addIndex(['id']);
161
            }
162
        }
163
164
        return $this;
165
    }
166
167
    public function setEntityPostfix($postfix)
168
    {
169
        $this->entityPostfix = $postfix;
170
        return $this;
171
    }
172
173
    public function setRepositoryPostfix($postfix)
174
    {
175
        $this->repositoryPostifx = $postfix;
176
        return $this;
177
    }
178
179
    private $spaceNames = [];
180
181
    public function getRepositorySpaceName($class)
182
    {
183
        return array_search($class, $this->repositoryMapping);
184
    }
185
186
    public function getSpaceName($class)
187
    {
188
        if (!array_key_exists($class, $this->spaceNames)) {
189
            $reflection = new ReflectionClass($class);
190
            $className = $reflection->getShortName();
191
192 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...
193
                if ($this->repositoryPostifx) {
194
                    $className = substr($className, 0, strlen($className) - strlen($this->repositoryPostifx));
195
                }
196
            }
197
198 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...
199
                if ($this->entityPostfix) {
200
                    $className = substr($className, 0, strlen($className) - strlen($this->entityPostfix));
201
                }
202
            }
203
204
            $this->spaceNames[$class] = $this->toUnderscore($className);
205
        }
206
207
        return $this->spaceNames[$class];
208
    }
209
210
    private $underscores = [];
211
212
    private function toUnderscore($input)
213
    {
214
        if (!array_key_exists($input, $this->underscores)) {
215
            preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
216
            $ret = $matches[0];
217
            foreach ($ret as &$match) {
218
                $match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
219
            }
220
            $this->underscores[$input] = implode('_', $ret);
221
        }
222
        return $this->underscores[$input];
223
    }
224
225
    private $tarantoolTypes = [];
226
227
    private function isReference(string $type)
228
    {
229
        return $type[0] == '\\';
230
    }
231
232
    private function getTarantoolType(string $type)
233
    {
234
        if (array_key_exists($type, $this->tarantoolTypes)) {
235
            return $this->tarantoolTypes[$type];
236
        }
237
238
        if ($this->isReference($type)) {
239
            return $this->tarantoolTypes[$type] = 'unsigned';
240
        }
241
242
        switch ($type) {
243
            case 'mixed':
244
            case 'array':
245
                return $this->tarantoolTypes[$type] = '*';
246
247
            case 'float':
248
                return $this->tarantoolTypes[$type] = 'float';
249
250
            case 'int':
251
                return $this->tarantoolTypes[$type] = 'unsigned';
252
253
            default:
254
                return $this->tarantoolTypes[$type] = 'str';
255
        }
256
    }
257
}
258