Completed
Push — master ( 351527...896a36 )
by Dmitry
01:56
created

Annotation::toUnderscore()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.2
c 0
b 0
f 0
cc 4
eloc 8
nc 2
nop 1
1
<?php
2
3
namespace Tarantool\Mapper\Plugin;
4
5
use Exception;
6
use phpDocumentor\Reflection\DocBlockFactory;
7
use phpDocumentor\Reflection\Types\ContextFactory;
8
use ReflectionClass;
9
use ReflectionProperty;
10
use Tarantool\Mapper\Entity;
11
use Tarantool\Mapper\Plugin\NestedSet;
12
use Tarantool\Mapper\Repository;
13
14
class Annotation extends UserClasses
15
{
16
    protected $entityClasses = [];
17
    protected $entityPostfix;
18
19
    protected $repositoryClasses = [];
20
    protected $repositoryPostifx;
21
22
    public function register($class)
23
    {
24
        $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...
25
        $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...
26
27
        if (!$isEntity && !$isRepository) {
28
            throw new Exception("Invalid registration");
29
        }
30
31
        if ($isEntity) {
32
            if ($class == Entity::class) {
33
                throw new Exception("Invalid entity registration");
34
            }
35
            $this->entityClasses[] = $class;
36
        }
37
38
        if ($isRepository) {
39
            if ($class == Repository::class) {
40
                throw new Exception("Invalid repository registration");
41
            }
42
            $this->repositoryClasses[] = $class;
43
        }
44
45
        $space = $this->getSpaceName($class);
46
        if ($isEntity) {
47
            $this->mapEntity($space, $class);
48
        } else {
49
            $this->mapRepository($space, $class);
50
        }
51
        return $this;
52
    }
53
54
    public function validateSpace($space)
55
    {
56
        foreach ($this->entityClasses as $class) {
57
            if ($this->getSpaceName($class) == $space) {
58
                return true;
59
            }
60
        }
61
62
        foreach ($this->repositoryClasses as $class) {
63
            if ($this->getSpaceName($class) == $space) {
64
                return true;
65
            }
66
        }
67
68
        return parent::validateSpace($space);
69
    }
70
71
    public function migrate()
72
    {
73
        $factory = DocBlockFactory::createInstance();
74
        $contextFactory = new ContextFactory();
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
                $context = $contextFactory->createFromReflector($property);
88
                $description = $factory->create($property->getDocComment(), $context);
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
                $propertyName = $this->mapper->getSchema()->toUnderscore($property->getName());
100
                $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...
101
                $type = $this->getTarantoolType($phpType);
102
103
                if (!$space->hasProperty($propertyName)) {
104
                    if ($this->isReference($phpType)) {
105
                        $space->addProperty($propertyName, $type, true, $this->getSpaceName((string) $phpType));
106
                    } else {
107
                        $space->addProperty($propertyName, $type);
108
                    }
109
                }
110
            }
111
            if ($this->mapper->hasPlugin(NestedSet::class)) {
112
                $nested = $this->mapper->getPlugin(NestedSet::class);
113
                if ($nested->isNested($space)) {
114
                    $nested->addIndexes($space);
115
                }
116
            }
117
        }
118
119
        foreach ($this->repositoryClasses as $repository) {
120
            $spaceName = $this->getSpaceName($repository);
121
122
            if (!$schema->hasSpace($spaceName)) {
123
                throw new Exception("Repository with no entity definition");
124
            }
125
126
            $this->mapRepository($spaceName, $repository);
127
128
            $space = $schema->getSpace($spaceName);
129
130
            $class = new ReflectionClass($repository);
131
            $properties = $class->getDefaultProperties();
132
133
            if (array_key_exists('indexes', $properties)) {
134
                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...
135
                    if (!is_array($index)) {
136
                        $index = (array) $index;
137
                    }
138
                    if (!array_key_exists('fields', $index)) {
139
                        $index = ['fields' => $index];
140
                    }
141
142
                    $index['if_not_exists'] = true;
143
                    try {
144
                        $space->addIndex($index);
145
                    } catch (Exception $e) {
146
                        $presentation = json_encode($properties['indexes'][$i]);
147
                        throw new Exception("Failed to add index $presentation. ". $e->getMessage(), 0, $e);
148
                    }
149
                }
150
            }
151
        }
152
153
        foreach ($schema->getSpaces() as $space) {
154
            if (!count($space->getIndexes())) {
155
                if (!$space->hasProperty('id')) {
156
                    throw new Exception("No primary index on ". $space->getName());
157
                }
158
                $space->addIndex(['id']);
159
            }
160
        }
161
162
        return $this;
163
    }
164
165
    public function setEntityPostfix($postfix)
166
    {
167
        $this->entityPostfix = $postfix;
168
        return $this;
169
    }
170
171
    public function setRepositoryPostfix($postfix)
172
    {
173
        $this->repositoryPostifx = $postfix;
174
        return $this;
175
    }
176
177
    private $spaceNames = [];
178
179
    public function getRepositorySpaceName($class)
180
    {
181
        return array_search($class, $this->repositoryMapping);
182
    }
183
184
    public function getSpaceName($class)
185
    {
186
        if (!array_key_exists($class, $this->spaceNames)) {
187
            $reflection = new ReflectionClass($class);
188
            $className = $reflection->getShortName();
189
190 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...
191
                if ($this->repositoryPostifx) {
192
                    $className = substr($className, 0, strlen($className) - strlen($this->repositoryPostifx));
193
                }
194
            }
195
196 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...
197
                if ($this->entityPostfix) {
198
                    $className = substr($className, 0, strlen($className) - strlen($this->entityPostfix));
199
                }
200
            }
201
202
            $this->spaceNames[$class] = $this->mapper->getSchema()->toUnderscore($className);
203
        }
204
205
        return $this->spaceNames[$class];
206
    }
207
208
    private $tarantoolTypes = [];
209
210
    private function isReference(string $type)
211
    {
212
        return $type[0] == '\\';
213
    }
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 ($this->isReference($type)) {
222
            return $this->tarantoolTypes[$type] = 'unsigned';
223
        }
224
225
        switch ($type) {
226
            case 'mixed':
227
            case 'array':
228
                return $this->tarantoolTypes[$type] = '*';
229
230
            case 'float':
231
                return $this->tarantoolTypes[$type] = 'number';
232
233
            case 'int':
234
                return $this->tarantoolTypes[$type] = 'unsigned';
235
236
            default:
237
                return $this->tarantoolTypes[$type] = 'string';
238
        }
239
    }
240
}
241