Completed
Push — master ( ceb702...82afac )
by Dmitry
01:41
created

Space::getName()   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 0
1
<?php
2
3
namespace Tarantool\Mapper;
4
5
use Exception;
6
use Tarantool\Client\Schema\Space as ClientSpace;
7
8
class Space
9
{
10
    private $mapper;
11
12
    private $id;
13
    private $name;
14
    private $format;
15
    private $indexes;
16
17
    private $formatNamesHash = [];
18
    private $formatTypesHash = [];
19
    private $formatReferences = [];
20
21
    private $repository;
22
23
    public function __construct(Mapper $mapper, $id, $name, $meta = null)
24
    {
25
        $this->mapper = $mapper;
26
        $this->id = $id;
27
        $this->name = $name;
28
29
        if ($meta) {
30
            foreach ($meta as $key => $value) {
31
                $this->$key = $value;
32
            }
33
        }
34
    }
35
36
    public function addProperties($config)
37
    {
38
        foreach ($config as $name => $type) {
39
            $this->addProperty($name, $type);
40
        }
41
        return $this;
42
    }
43
44
    public function addProperty($name, $type, $is_nullable = true, $reference = null)
45
    {
46
        $format = $this->getFormat();
47
        foreach ($format as $field) {
48
            if ($field['name'] == $name) {
49
                throw new Exception("Property $name exists");
50
            }
51
        }
52
        $row = compact('name', 'type', 'is_nullable');
53
        if ($reference) {
54
            $row['reference'] = $reference;
55
        }
56
        $format[] = $row;
57
        $this->format = $format;
58
        $this->mapper->getClient()->evaluate("box.space[$this->id]:format(...)", [$format]);
59
60
        $this->parseFormat();
61
62
        return $this;
63
    }
64
65
    public function isPropertyNullable($name)
66
    {
67
        foreach ($this->getFormat() as $field) {
68
            if ($field['name'] == $name) {
69
                return array_key_exists('is_nullable', $field) ? $field['is_nullable'] : false;
70
            }
71
        }
72
    }
73
74
    public function setPropertyNullable($name, $nullable = true)
75
    {
76
        $format = $this->getFormat();
77
        foreach ($format as $i => $field) {
78
            if ($field['name'] == $name) {
79
                $format[$i]['is_nullable'] = $nullable;
80
            }
81
        }
82
        $this->format = $format;
83
        $this->mapper->getClient()->evaluate("box.space[$this->id]:format(...)", [$format]);
84
85
        $this->parseFormat();
86
87
        return $this;
88
    }
89
90
    public function removeProperty($name)
91
    {
92
        $format = $this->getFormat();
93
        $last = array_pop($format);
94
        if ($last['name'] != $name) {
95
            throw new Exception("Remove only last property");
96
        }
97
        $this->mapper->getClient()->evaluate("box.space[$this->id]:format(...)", [$format]);
98
        $this->format = $format;
99
100
        $this->parseFormat();
101
102
        return $this;
103
    }
104
105
    public function removeIndex($name)
106
    {
107
        $this->mapper->getClient()->evaluate("box.space[$this->id].index.$name:drop()");
108
        $this->indexes = [];
109
        $this->mapper->getRepository('_vindex')->flushCache();
110
111
        return $this;
112
    }
113
114
    public function addIndex($config)
115
    {
116
        return $this->createIndex($config);
117
    }
118
119
    public function createIndex($config)
120
    {
121
        if (!is_array($config)) {
122
            $config = ['fields' => $config];
123
        }
124
125
126
        if (!array_key_exists('fields', $config)) {
127
            if (array_values($config) != $config) {
128
                throw new Exception("Invalid index configuration");
129
            }
130
            $config = [
131
                'fields' => $config
132
            ];
133
        }
134
135
        if (!is_array($config['fields'])) {
136
            $config['fields'] = [$config['fields']];
137
        }
138
139
        $options = [
140
            'parts' => []
141
        ];
142
143
        foreach ($config as $k => $v) {
144
            if ($k != 'name' && $k != 'fields') {
145
                $options[$k] = $v;
146
            }
147
        }
148
149
        foreach ($config['fields'] as $property) {
150
            if (!$this->getPropertyType($property)) {
151
                throw new Exception("Unknown property $property", 1);
152
            }
153
            $options['parts'][] = $this->getPropertyIndex($property)+1;
154
            $options['parts'][] = $this->getPropertyType($property);
155
            $this->setPropertyNullable($property, false);
156
        }
157
158
        $name = array_key_exists('name', $config) ? $config['name'] : implode('_', $config['fields']);
159
160
        $this->mapper->getClient()->evaluate("box.space[$this->id]:create_index('$name', ...)", [$options]);
161
        $this->indexes = [];
162
163
        $this->mapper->getSchema()->getSpace('_vindex')->getRepository()->flushCache();
164
165
        return $this;
166
    }
167
168
    public function getIndexType($id)
169
    {
170
        foreach ($this->getIndexes() as $index) {
171
            if ($index['iid'] == $id) {
172
                return $index['type'];
173
            }
174
        }
175
176
        throw new Exception("Invalid index #$index");
177
    }
178
179
    public function isSpecial()
180
    {
181
        return $this->id == ClientSpace::VSPACE || $this->id == ClientSpace::VINDEX;
182
    }
183
184
    public function getId()
185
    {
186
        return $this->id;
187
    }
188
189
    public function getTupleMap()
190
    {
191
        $reverse = [];
192
        foreach ($this->getFormat() as $i => $field) {
193
            $reverse[$field['name']] = $i + 1;
194
        }
195
        return (object) $reverse;
196
    }
197
198
    public function getFormat()
199
    {
200
        if (!$this->format) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->format of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
201
            if ($this->isSpecial()) {
202
                $this->format = $this->mapper->getClient()
203
                    ->getSpace(ClientSpace::VSPACE)->select([$this->id])->getData()[0][6];
204
            } else {
205
                $this->format = $this->mapper->findOne('_vspace', ['id' => $this->id])->format;
206
            }
207
            if (!$this->format) {
208
                $this->format = [];
209
            }
210
            $this->parseFormat();
211
        }
212
213
        return $this->format;
214
    }
215
216
    public function getMapper()
217
    {
218
        return $this->mapper;
219
    }
220
221
    public function getName()
222
    {
223
        return $this->name;
224
    }
225
226
    private function parseFormat()
227
    {
228
        $this->formatTypesHash = [];
229
        $this->formatNamesHash = [];
230
        $this->formatReferences = [];
231
        foreach ($this->format as $key => $row) {
232
            $this->formatTypesHash[$row['name']] = $row['type'];
233
            $this->formatNamesHash[$row['name']] = $key;
234
            if (array_key_exists('reference', $row)) {
235
                $this->formatReferences[$row['name']] = $row['reference'];
236
            }
237
        }
238
        return $this;
239
    }
240
241
    public function hasProperty($name)
242
    {
243
        $this->getFormat();
244
        return array_key_exists($name, $this->formatNamesHash);
245
    }
246
247
    public function getMeta()
248
    {
249
        $this->getFormat();
250
        $this->getIndexes();
251
252
        return [
253
            'formatNamesHash' => $this->formatNamesHash,
254
            'formatTypesHash' => $this->formatTypesHash,
255
            'formatReferences' => $this->formatReferences,
256
            'indexes' => $this->indexes,
257
            'format' => $this->format,
258
        ];
259
    }
260
261
    public function getPropertyType($name)
262
    {
263
        if (!$this->hasProperty($name)) {
264
            throw new Exception("No property $name");
265
        }
266
        return $this->formatTypesHash[$name];
267
    }
268
269
    public function getPropertyIndex($name)
270
    {
271
        if (!$this->hasProperty($name)) {
272
            throw new Exception("No property $name");
273
        }
274
        return $this->formatNamesHash[$name];
275
    }
276
277
    public function getReference($name)
278
    {
279
        return $this->isReference($name) ? $this->formatReferences[$name] : null;
280
    }
281
282
    public function isReference($name)
283
    {
284
        return array_key_exists($name, $this->formatReferences);
285
    }
286
287
    public function getIndexes()
288
    {
289
        if (!$this->indexes) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->indexes of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
290
            if ($this->isSpecial()) {
291
                $this->indexes = [];
292
                $indexTuples = $this->mapper->getClient()->getSpace(ClientSpace::VINDEX)->select([$this->id])->getData();
293
                $indexFormat = $this->mapper->getSchema()->getSpace(ClientSpace::VINDEX)->getFormat();
294
                foreach ($indexTuples as $tuple) {
0 ignored issues
show
Bug introduced by
The expression $indexTuples of type null|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...
295
                    $instance = [];
296
                    foreach ($indexFormat as $index => $format) {
297
                        $instance[$format['name']] = $tuple[$index];
298
                    }
299
                    $this->indexes[] = $instance;
300
                }
301
            } else {
302
                $indexes = $this->mapper->find('_vindex', ['id' => $this->id]);
303
                $this->indexes = [];
304
                foreach ($indexes as $index) {
305
                    $index = get_object_vars($index);
306
                    foreach ($index as $key => $value) {
307
                        if (is_object($value)) {
308
                            unset($index[$key]);
309
                        }
310
                    }
311
                    $this->indexes[] = $index;
312
                }
313
            }
314
        }
315
        return $this->indexes;
316
    }
317
318
    public function castIndex($params, $suppressException = false)
319
    {
320
        if (!count($this->getIndexes())) {
321
            return;
322
        }
323
        $keys = array_keys($params);
0 ignored issues
show
Unused Code introduced by
$keys is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
324
325
        $keys = [];
326
        foreach ($params as $name => $value) {
327
            $keys[] = $this->getPropertyIndex($name);
328
        }
329
330
        // equals
331
        foreach ($this->getIndexes() as $index) {
332
            $equals = false;
333
            if (count($keys) == count($index['parts'])) {
334
                // same length
335
                $equals = true;
336
                foreach ($index['parts'] as $part) {
337
                    $equals = $equals && in_array($part[0], $keys);
338
                }
339
            }
340
341
            if ($equals) {
342
                return $index['iid'];
343
            }
344
        }
345
346
        // index part
347
        foreach ($this->getIndexes() as $index) {
348
            $partial = [];
349
            foreach ($index['parts'] as $n => $part) {
350
                if (!array_key_exists($n, $keys)) {
351
                    break;
352
                }
353
                if ($keys[$n] != $part[0]) {
354
                    break;
355
                }
356
                $partial[] = $keys[$n];
357
            }
358
359
            if (count($partial) == count($keys)) {
360
                return $index['iid'];
361
            }
362
        }
363
364
        if (!$suppressException) {
365
            throw new Exception("No index");
366
        }
367
    }
368
369
    public function getIndexValues($indexId, $params)
370
    {
371
        $index = null;
372
        foreach ($this->getIndexes() as $candidate) {
373
            if ($candidate['iid'] == $indexId) {
374
                $index = $candidate;
375
                break;
376
            }
377
        }
378
        if (!$index) {
379
            throw new Exception("Undefined index: $indexId");
380
        }
381
382
        $format = $this->getFormat();
383
        $values = [];
384
        foreach ($index['parts'] as $part) {
385
            $name = $format[$part[0]]['name'];
386
            if (!array_key_exists($name, $params)) {
387
                break;
388
            }
389
            $value = $this->mapper->getSchema()->formatValue($part[1], $params[$name]);
390
            if (is_null($value) && !$this->isPropertyNullable($name)) {
391
                $value = $this->mapper->getSchema()->getDefaultValue($format[$part[0]]['type']);
392
            }
393
            $values[] = $value;
394
        }
395
        return $values;
396
    }
397
398
    public function getPrimaryIndex()
399
    {
400
        $indexes = $this->getIndexes();
401
        if (!count($indexes)) {
402
            throw new Exception("No primary index");
403
        }
404
        return $indexes[0];
405
    }
406
407
    public function getTupleKey($tuple)
408
    {
409
        $key = [];
410
        foreach ($this->getPrimaryIndex()['parts'] as $part) {
411
            $key[] = $tuple[$part[0]];
412
        }
413
        return count($key) == 1 ? $key[0] : implode(':', $key);
414
    }
415
416
    public function getInstanceKey($instance)
417
    {
418
        $key = [];
419
420
        foreach ($this->getPrimaryIndex()['parts'] as $part) {
421
            $name = $this->getFormat()[$part[0]]['name'];
422
            if (!property_exists($instance, $name)) {
423
                throw new Exception("Field $name is undefined", 1);
424
            }
425
            $key[] = $instance->$name;
426
        }
427
428
        return count($key) == 1 ? $key[0] : implode(':', $key);
429
    }
430
431
    public function getRepository()
432
    {
433
        $class = Repository::class;
434
        foreach ($this->mapper->getPlugins() as $plugin) {
435
            $repositoryClass = $plugin->getRepositoryClass($this);
436
            if ($repositoryClass) {
437
                if ($class != Repository::class) {
438
                    throw new Exception('Repository class override');
439
                }
440
                $class = $repositoryClass;
441
            }
442
        }
443
        return $this->repository ?: $this->repository = new $class($this);
444
    }
445
446
    public function repositoryExists()
447
    {
448
        return !!$this->repository;
449
    }
450
}
451