Completed
Push — master ( 6628b2...2cce3e )
by Dmitry
02:18
created

Annotation::getRepositorySpaceName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
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 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 ($this->mapper->getSchema()->hasSpace($space)) {
48
            if ($isEntity) {
49
                $this->mapEntity($space, $class);
50
            } else {
51
                $singulared = false;
52
                foreach ($this->entityMapping as $candidate => $_class) {
53
                    if ($this->pluralize($candidate) == $space) {
54
                        $space = $candidate;
55
                        $singulared = true;
56
                        break;
57
                    }
58
                }
59
                if (!$singulared) {
60
                    foreach ($this->mapper->getSchema()->getSpaces() as $space) {
61
                        if ($this->pluralize($space->getName()) == $space) {
62
                            $space = $candidate;
0 ignored issues
show
Bug introduced by
The variable $candidate seems to be defined by a foreach iteration on line 52. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
63
                            break;
64
                        }
65
                    }
66
                }
67
                $this->mapRepository($space, $class);
68
            }
69
        }
70
        return $this;
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
        }
107
108
        $plural = [];
109
        foreach ($this->mapper->getSchema()->getSpaces() as $space) {
110
            $plural[$this->pluralize($space->getName())] = $space->getName();
111
        }
112
113
        foreach ($this->repositoryClasses as $repository) {
114
            $spaceName = $this->getSpaceName($repository);
115
116
            if (array_key_exists($spaceName, $plural)) {
117
                $spaceName = $plural[$spaceName];
118
            }
119
120
            if (!$schema->hasSpace($spaceName)) {
121
                throw new Exception("Repository with no entity definition");
122
            }
123
124
            $this->mapRepository($spaceName, $repository);
125
126
            $space = $schema->getSpace($spaceName);
127
128
            $class = new ReflectionClass($repository);
129
            $properties = $class->getDefaultProperties();
130
131
            if (array_key_exists('indexes', $properties)) {
132
                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...
133
                    if (!is_array($index)) {
134
                        $index = (array) $index;
135
                    }
136
                    if (!array_key_exists('fields', $index)) {
137
                        $index = ['fields' => $index];
138
                    }
139
140
                    $index['if_not_exists'] = true;
141
                    $space->addIndex($index);
142
                }
143
            }
144
        }
145
146
        foreach ($schema->getSpaces() as $space) {
147
            if (!count($space->getIndexes())) {
148
                if (!$space->hasProperty('id')) {
149
                    throw new Exception("No primary index on ". $space->getName());
150
                }
151
                $space->addIndex(['id']);
152
            }
153
        }
154
155
        return $this;
156
    }
157
158
    public function setEntityPostfix($postfix)
159
    {
160
        $this->entityPostfix = $postfix;
161
        return $this;
162
    }
163
164
    public function setRepositoryPostfix($postfix)
165
    {
166
        $this->repositoryPostifx = $postfix;
167
        return $this;
168
    }
169
170
    private $spaceNames = [];
171
172
    public function getRepositorySpaceName($class)
173
    {
174
        return array_search($class, $this->repositoryMapping);
175
    }
176
177
    public function getSpaceName($class)
178
    {
179
        if (!array_key_exists($class, $this->spaceNames)) {
180
            $reflection = new ReflectionClass($class);
181
            $className = $reflection->getShortName();
182
183 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...
184
                if ($this->repositoryPostifx) {
185
                    $className = substr($className, 0, strlen($className) - strlen($this->repositoryPostifx));
186
                }
187
            }
188
189 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...
190
                if ($this->entityPostfix) {
191
                    $className = substr($className, 0, strlen($className) - strlen($this->entityPostfix));
192
                }
193
            }
194
195
            $this->spaceNames[$class] = $this->toUnderscore($className);
196
        }
197
198
        return $this->spaceNames[$class];
199
    }
200
201
    private function pluralize($word)
202
    {
203
        switch (strtolower($word[strlen($word)-1])) {
204
            case 'y':
205
                return substr($word, 0, -1).'ies';
206
            case 's':
207
                return $word.'es';
208
            default:
209
                return $word.'s';
210
        }
211
    }
212
213
    private $underscores = [];
214
215
    private function toUnderscore($input)
216
    {
217
        if (!array_key_exists($input, $this->underscores)) {
218
            preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
219
            $ret = $matches[0];
220
            foreach ($ret as &$match) {
221
                $match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
222
            }
223
            $this->underscores[$input] = implode('_', $ret);
224
        }
225
        return $this->underscores[$input];
226
    }
227
228
    private $tarantoolTypes = [];
229
230
    private function getTarantoolType(string $type)
231
    {
232
        if (array_key_exists($type, $this->tarantoolTypes)) {
233
            return $this->tarantoolTypes[$type];
234
        }
235
236
        if ($type[0] == '\\') {
237
            return $this->tarantoolTypes[$type] = 'unsigned';
238
        }
239
240
        switch ($type) {
241
            case 'int':
242
                return $this->tarantoolTypes[$type] = 'unsigned';
243
244
            default:
245
                return $this->tarantoolTypes[$type] = 'str';
246
        }
247
    }
248
}
249