Completed
Push — master ( fd6099...02f858 )
by Dmitry
02:20
created

Annotation::validateSpace()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4222
c 0
b 0
f 0
cc 5
nc 7
nop 1
1
<?php
2
3
namespace Tarantool\Mapper\Plugin;
4
5
use Closure;
6
use Exception;
7
use LogicException;
8
use phpDocumentor\Reflection\DocBlockFactory;
9
use phpDocumentor\Reflection\Types\ContextFactory;
10
use ReflectionClass;
11
use ReflectionMethod;
12
use ReflectionProperty;
13
use Tarantool\Mapper\Entity;
14
use Tarantool\Mapper\Plugin\NestedSet;
15
use Tarantool\Mapper\Repository;
16
use Tarantool\Mapper\Space;
17
18
class Annotation extends UserClasses
19
{
20
    protected $entityClasses = [];
21
    protected $entityPostfix;
22
23
    protected $repositoryClasses = [];
24
    protected $repositoryPostifx;
25
26
    protected $extensions;
27
28
    public function register($class)
29
    {
30
        $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...
31
        $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...
32
33
        if (!$isEntity && !$isRepository) {
34
            throw new Exception("Invalid registration for $class");
35
        }
36
37
        if ($isEntity) {
38
            if ($class == Entity::class) {
39
                throw new Exception("Invalid entity registration for $class");
40
            }
41
            $this->entityClasses[] = $class;
42
        }
43
44
        if ($isRepository) {
45
            if ($class == Repository::class) {
46
                throw new Exception("Invalid repository registration for $class");
47
            }
48
            $this->repositoryClasses[] = $class;
49
        }
50
51
        $space = $this->getSpaceName($class);
52
        if ($isEntity) {
53
            $this->mapEntity($space, $class);
54
        } else {
55
            $this->mapRepository($space, $class);
56
        }
57
        return $this;
58
    }
59
60
    public function validateSpace($space)
61
    {
62
        foreach ($this->entityClasses as $class) {
63
            if ($this->getSpaceName($class) == $space) {
64
                return true;
65
            }
66
        }
67
68
        foreach ($this->repositoryClasses as $class) {
69
            if ($this->getSpaceName($class) == $space) {
70
                return true;
71
            }
72
        }
73
74
        return parent::validateSpace($space);
75
    }
76
77
    public function getSpace($instance)
78
    {
79
        $class = get_class($instance);
80
        $target = $this->isExtension($class) ? $this->getExtensions()[$class] : $class;
81
        return $this->getSpaceName($target);
82
    }
83
84
    public function isExtension($class)
85
    {
86
        return array_key_exists($class, $this->getExtensions());
87
    }
88
89
    public function getExtensions()
90
    {
91
        if (is_null($this->extensions)) {
92
            $this->extensions = [];
93
            foreach ($this->entityClasses as $entity) {
94
                $reflection = new ReflectionClass($entity);
95
                $parentEntity = $reflection->getParentClass()->getName();
96
                if (in_array($parentEntity, $this->entityClasses)) {
97
                    $this->extensions[$entity] = $parentEntity;
98
                }
99
            }
100
        }
101
        return $this->extensions;
102
    }
103
104
    public function migrate($extensionInstances = true)
105
    {
106
        $factory = DocBlockFactory::createInstance();
107
        $contextFactory = new ContextFactory();
108
109
        $schema = $this->mapper->getSchema();
110
111
        $computes = [];
112
        foreach ($this->entityClasses as $entity) {
113
            if ($this->isExtension($entity)) {
114
                continue;
115
            }
116
117
            $spaceName = $this->getSpaceName($entity);
118
119
            $engine = 'memtx';
120
            if (array_key_exists($spaceName, $this->repositoryMapping)) {
121
                $repositoryClass = $this->repositoryMapping[$spaceName];
122
                $repositoryReflection = new ReflectionClass($repositoryClass);
123
                $repositoryProperties = $repositoryReflection->getDefaultProperties();
124
                if (array_key_exists('engine', $repositoryProperties)) {
125
                    $engine = $repositoryProperties['engine'];
126
                }
127
            }
128
129
            if ($schema->hasSpace($spaceName)) {
130
                $space = $schema->getSpace($spaceName);
131
                if ($space->getEngine() != $engine) {
132
                    throw new Exception("Space engine can't be updated");
133
                }
134
            } else {
135
                $space = $schema->createSpace($spaceName, [
136
                    'engine' => $engine,
137
                    'properties' => [],
138
                ]);
139
            }
140
141
            $class = new ReflectionClass($entity);
142
143
            foreach ($class->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
144
                $context = $contextFactory->createFromReflector($property);
145
                $description = $factory->create($property->getDocComment(), $context);
146
                $tags = $description->getTags('var');
147
148
                if (!count($tags)) {
149
                    throw new Exception("No var tag for ".$entity.'::'.$property->getName());
150
                }
151
152
                $byTypes = [];
153
                foreach ($tags as $candidate) {
154
                    $byTypes[$candidate->getName()] = $candidate;
155
                }
156
157
                if (!array_key_exists('var', $byTypes)) {
158
                    throw new Exception("No var tag for ".$entity.'::'.$property->getName());
159
                }
160
161
                $propertyName = $property->getName();
162
                $phpType = $byTypes['var']->getType();
163
164
                if (array_key_exists('type', $byTypes)) {
165
                    $type = (string) $byTypes['type']->getDescription();
166
                } else {
167
                    $type = $this->getTarantoolType($phpType);
168
                }
169
170
                $isNullable = true;
171
172
                if (array_key_exists('required', $byTypes)) {
173
                    $isNullable = false;
174
                }
175
176
                if (!$space->hasProperty($propertyName)) {
177
                    $opts = [
178
                        'is_nullable' => $isNullable,
179
                    ];
180
                    if ($this->isReference($phpType)) {
181
                        $opts['reference'] = $this->getSpaceName((string) $phpType);
182
                    }
183
                    if (array_key_exists('default', $byTypes)) {
184
                        $opts['default'] = $schema->formatValue($type, (string) $byTypes['default']);
185
                    }
186
                    $space->addProperty($propertyName, $type, $opts);
187
                }
188
            }
189
            if ($this->mapper->hasPlugin(NestedSet::class)) {
190
                $nested = $this->mapper->getPlugin(NestedSet::class);
191
                if ($nested->isNested($space)) {
192
                    $nested->addIndexes($space);
193
                }
194
            }
195
            if (in_array($entity, $this->extensions)) {
196
                if (!$space->hasProperty('class')) {
197
                    throw new Exception("$entity has extensions, but not class property is defined");
198
                }
199
                $space->addIndex('class');
200
            }
201
202
            if ($class->hasMethod('compute')) {
203
                $computes[] = $spaceName;
204
            }
205
        }
206
207
208
        foreach ($this->repositoryClasses as $repository) {
209
            $spaceName = $this->getSpaceName($repository);
210
211
            if (!$schema->hasSpace($spaceName)) {
212
                throw new Exception("Repository $spaceName has no entity definition");
213
            }
214
215
            $this->mapRepository($spaceName, $repository);
216
217
            $space = $schema->getSpace($spaceName);
218
219
            $class = new ReflectionClass($repository);
220
            $properties = $class->getDefaultProperties();
221
222
            if (array_key_exists('indexes', $properties)) {
223
                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...
224
                    if (!is_array($index)) {
225
                        $index = (array) $index;
226
                    }
227
                    if (!array_key_exists('fields', $index)) {
228
                        $index = ['fields' => $index];
229
                    }
230
231
                    $index['if_not_exists'] = true;
232
                    try {
233
                        $space->addIndex($index);
234
                    } catch (Exception $e) {
235
                        $presentation = json_encode($properties['indexes'][$i]);
236
                        throw new Exception("Failed to add index $presentation. ". $e->getMessage(), 0, $e);
237
                    }
238
                }
239
            }
240
        }
241
        foreach ($schema->getSpaces() as $space) {
242
            if ($space->isSystem()) {
243
                continue;
244
            }
245
            if (!count($space->getIndexes())) {
246
                if (!$space->hasProperty('id')) {
247
                    throw new Exception("No primary index on ". $space->getName());
248
                }
249
                $space->addIndex(['id']);
250
            }
251
        }
252
253
        foreach ($computes as $spaceName) {
254
            $method = new ReflectionMethod($this->entityMapping[$spaceName], 'compute');
255
            $type = (string) $method->getParameters()[0]->getType();
256
            $sourceSpace = array_search($type, $this->entityMapping);
257
            if (!$sourceSpace) {
258
                throw new Exception("Invalid compute source $type");
259
            }
260
            $compute = Closure::fromCallable([$this->entityMapping[$spaceName], 'compute']);
261
            $this->mapper->getPlugin(Compute::class)->register($sourceSpace, $spaceName, $compute);
262
        }
263
264
        if ($extensionInstances) {
265
            foreach ($this->extensions as $class => $target) {
266
                $space = $this->getSpaceName($target);
267
                $this->mapper->findOrCreate($space, [
268
                    'class' => $class,
269
                ]);
270
            }
271
        }
272
273
        return $this;
274
    }
275
276
    public function getEntityClass(Space $space, array $data)
277
    {
278
        $class = parent::getEntityClass($space, $data);
279
        if (in_array($class, $this->getExtensions())) {
280
            if (!array_key_exists('class', $data) || !$data['class']) {
281
                throw new LogicException("Extension without class defined");
282
            }
283
            return $data['class'];
284
        }
285
        return $class;
286
    }
287
288
    public function setEntityPostfix($postfix)
289
    {
290
        $this->entityPostfix = $postfix;
291
        return $this;
292
    }
293
294
    public function setRepositoryPostfix($postfix)
295
    {
296
        $this->repositoryPostifx = $postfix;
297
        return $this;
298
    }
299
300
    private $spaceNames = [];
301
302
    public function getRepositorySpaceName($class)
303
    {
304
        return array_search($class, $this->repositoryMapping);
305
    }
306
307
    public function getSpaceName($class)
308
    {
309
        if (!array_key_exists($class, $this->spaceNames)) {
310
            $reflection = new ReflectionClass($class);
311
            $className = $reflection->getShortName();
312
313 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...
314
                if ($this->repositoryPostifx) {
315
                    $className = substr($className, 0, strlen($className) - strlen($this->repositoryPostifx));
316
                }
317
            }
318
319 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...
320
                if ($this->entityPostfix) {
321
                    $className = substr($className, 0, strlen($className) - strlen($this->entityPostfix));
322
                }
323
            }
324
325
            $this->spaceNames[$class] = $this->mapper->getSchema()->toUnderscore($className);
326
        }
327
328
        return $this->spaceNames[$class];
329
    }
330
331
    private $tarantoolTypes = [];
332
333
    private function isReference(string $type)
334
    {
335
        return $type[0] == '\\';
336
    }
337
338
    private function getTarantoolType(string $type)
339
    {
340
        if (array_key_exists($type, $this->tarantoolTypes)) {
341
            return $this->tarantoolTypes[$type];
342
        }
343
344
        if ($this->isReference($type)) {
345
            return $this->tarantoolTypes[$type] = 'unsigned';
346
        }
347
348
        switch ($type) {
349
            case 'mixed':
350
            case 'array':
351
                return $this->tarantoolTypes[$type] = '*';
352
353
            case 'float':
354
                return $this->tarantoolTypes[$type] = 'number';
355
356
            case 'int':
357
                return $this->tarantoolTypes[$type] = 'unsigned';
358
359
            default:
360
                return $this->tarantoolTypes[$type] = 'string';
361
        }
362
    }
363
}
364