Completed
Push — master ( 43d7fb...779a1c )
by Dmitry
03:34
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 Closure;
6
use Exception;
7
use phpDocumentor\Reflection\DocBlockFactory;
8
use phpDocumentor\Reflection\Types\ContextFactory;
9
use ReflectionClass;
10
use ReflectionMethod;
11
use ReflectionProperty;
12
use Tarantool\Mapper\Entity;
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 for $class");
31
        }
32
33
        if ($isEntity) {
34
            if ($class == Entity::class) {
35
                throw new Exception("Invalid entity registration for $class");
36
            }
37
            $this->entityClasses[] = $class;
38
        }
39
40
        if ($isRepository) {
41
            if ($class == Repository::class) {
42
                throw new Exception("Invalid repository registration for $class");
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
        $computes = [];
81
        foreach ($this->entityClasses as $entity) {
82
83
            $spaceName = $this->getSpaceName($entity);
84
85
            $engine = 'memtx';
86
            if (array_key_exists($spaceName, $this->repositoryMapping)) {
87
                $repositoryClass = $this->repositoryMapping[$spaceName];
88
                $repositoryReflection = new ReflectionClass($repositoryClass);
89
                $repositoryProperties = $repositoryReflection->getDefaultProperties();
90
                if (array_key_exists('engine', $repositoryProperties)) {
91
                    $engine = $repositoryProperties['engine'];
92
                }
93
            }
94
95
            if ($schema->hasSpace($spaceName)) {
96
                $space = $schema->getSpace($spaceName);
97
                if ($space->getEngine() != $engine) {
98
                    throw new Exception("Space engine can't be updated");
99
                }
100
            } else {
101
                $space = $schema->createSpace($spaceName, [
102
                    'engine' => $engine,
103
                    'properties' => [],
104
                ]);
105
            }
106
107
            $class = new ReflectionClass($entity);
108
109
            foreach ($class->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
110
                $context = $contextFactory->createFromReflector($property);
111
                $description = $factory->create($property->getDocComment(), $context);
112
                $tags = $description->getTags('var');
113
114 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...
115
                    throw new Exception("No var tag for ".$entity.'::'.$property->getName());
116
                }
117
118 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...
119
                    throw new Exception("Invalid var tag for ".$entity.'::'.$property->getName());
120
                }
121
122
                $propertyName = $property->getName();
123
                $phpType = $tags[0]->getType();
124
                $type = $this->getTarantoolType($phpType);
125
126
                if (!$space->hasProperty($propertyName)) {
127
                    if ($this->isReference($phpType)) {
128
                        $space->addProperty($propertyName, $type, true, $this->getSpaceName((string) $phpType));
129
                    } else {
130
                        $space->addProperty($propertyName, $type);
131
                    }
132
                }
133
            }
134
            if ($this->mapper->hasPlugin(NestedSet::class)) {
135
                $nested = $this->mapper->getPlugin(NestedSet::class);
136
                if ($nested->isNested($space)) {
137
                    $nested->addIndexes($space);
138
                }
139
            }
140
141
            if ($class->hasMethod('compute')) {
142
                $computes[] = $spaceName;
143
            }
144
        }
145
146
147
        foreach ($this->repositoryClasses as $repository) {
148
            $spaceName = $this->getSpaceName($repository);
149
150
            if (!$schema->hasSpace($spaceName)) {
151
                throw new Exception("Repository $spaceName has no entity definition");
152
            }
153
154
            $this->mapRepository($spaceName, $repository);
155
156
            $space = $schema->getSpace($spaceName);
157
158
            $class = new ReflectionClass($repository);
159
            $properties = $class->getDefaultProperties();
160
161
            if (array_key_exists('indexes', $properties)) {
162
                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...
163
                    if (!is_array($index)) {
164
                        $index = (array) $index;
165
                    }
166
                    if (!array_key_exists('fields', $index)) {
167
                        $index = ['fields' => $index];
168
                    }
169
170
                    $index['if_not_exists'] = true;
171
                    try {
172
                        $space->addIndex($index);
173
                    } catch (Exception $e) {
174
                        $presentation = json_encode($properties['indexes'][$i]);
175
                        throw new Exception("Failed to add index $presentation. ". $e->getMessage(), 0, $e);
176
                    }
177
                }
178
            }
179
        }
180
        foreach ($schema->getSpaces() as $space) {
181
            if (!count($space->getIndexes())) {
182
                if (!$space->hasProperty('id')) {
183
                    throw new Exception("No primary index on ". $space->getName());
184
                }
185
                $space->addIndex(['id']);
186
            }
187
        }
188
189
        foreach ($computes as $spaceName) {
190
            $method = new ReflectionMethod($this->entityMapping[$spaceName], 'compute');
191
            $type = (string) $method->getParameters()[0]->getType();
192
            $sourceSpace = array_search($type, $this->entityMapping);
193
            if (!$sourceSpace) {
194
                throw new Exception("Invalid compute source $type");
195
            }
196
            $compute = Closure::fromCallable([$this->entityMapping[$spaceName], 'compute']);
197
            $this->mapper->getPlugin(Compute::class)->register($sourceSpace, $spaceName, $compute);
198
        }
199
200
        return $this;
201
    }
202
203
    public function setEntityPostfix($postfix)
204
    {
205
        $this->entityPostfix = $postfix;
206
        return $this;
207
    }
208
209
    public function setRepositoryPostfix($postfix)
210
    {
211
        $this->repositoryPostifx = $postfix;
212
        return $this;
213
    }
214
215
    private $spaceNames = [];
216
217
    public function getRepositorySpaceName($class)
218
    {
219
        return array_search($class, $this->repositoryMapping);
220
    }
221
222
    public function getSpaceName($class)
223
    {
224
        if (!array_key_exists($class, $this->spaceNames)) {
225
            $reflection = new ReflectionClass($class);
226
            $className = $reflection->getShortName();
227
228 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...
229
                if ($this->repositoryPostifx) {
230
                    $className = substr($className, 0, strlen($className) - strlen($this->repositoryPostifx));
231
                }
232
            }
233
234 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...
235
                if ($this->entityPostfix) {
236
                    $className = substr($className, 0, strlen($className) - strlen($this->entityPostfix));
237
                }
238
            }
239
240
            $this->spaceNames[$class] = $this->mapper->getSchema()->toUnderscore($className);
241
        }
242
243
        return $this->spaceNames[$class];
244
    }
245
246
    private $tarantoolTypes = [];
247
248
    private function isReference(string $type)
249
    {
250
        return $type[0] == '\\';
251
    }
252
253
    private function getTarantoolType(string $type)
254
    {
255
        if (array_key_exists($type, $this->tarantoolTypes)) {
256
            return $this->tarantoolTypes[$type];
257
        }
258
259
        if ($this->isReference($type)) {
260
            return $this->tarantoolTypes[$type] = 'unsigned';
261
        }
262
263
        switch ($type) {
264
            case 'mixed':
265
            case 'array':
266
                return $this->tarantoolTypes[$type] = '*';
267
268
            case 'float':
269
                return $this->tarantoolTypes[$type] = 'number';
270
271
            case 'int':
272
                return $this->tarantoolTypes[$type] = 'unsigned';
273
274
            default:
275
                return $this->tarantoolTypes[$type] = 'string';
276
        }
277
    }
278
}
279