|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Tarantool\Mapper\Plugin; |
|
4
|
|
|
|
|
5
|
|
|
use Tarantool\Mapper\Entity; |
|
6
|
|
|
use Tarantool\Mapper\Plugin; |
|
7
|
|
|
use Tarantool\Mapper\Space; |
|
8
|
|
|
|
|
9
|
|
|
class Sequence extends Plugin |
|
10
|
|
|
{ |
|
11
|
|
|
public function generateKey(Entity $instance, Space $space) |
|
12
|
|
|
{ |
|
13
|
|
|
$primary = $space->getPrimaryIndex(); |
|
14
|
|
|
if (count($primary['parts']) == 1) { |
|
15
|
|
|
$key = $space->getFormat()[$primary['parts'][0][0]]['name']; |
|
16
|
|
|
if (!property_exists($instance, $key) || is_null($instance->$key)) { |
|
17
|
|
|
$instance->$key = $this->generateValue($space); |
|
18
|
|
|
} |
|
19
|
|
|
} |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
|
|
public function initSchema() |
|
23
|
|
|
{ |
|
24
|
|
|
if (!$this->mapper->getSchema()->hasSpace('sequence')) { |
|
25
|
|
|
$sequence = $this->mapper->getSchema()->createSpace('sequence'); |
|
26
|
|
|
$sequence->addProperty('space', 'unsigned'); |
|
27
|
|
|
$sequence->addProperty('counter', 'unsigned'); |
|
28
|
|
|
$sequence->createIndex('space'); |
|
29
|
|
|
} |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
private function generateValue($space) |
|
33
|
|
|
{ |
|
34
|
|
|
$this->initSchema(); |
|
35
|
|
|
|
|
36
|
|
|
$spaceId = $space->getId(); |
|
|
|
|
|
|
37
|
|
|
$entity = $this->mapper->findOne('sequence', $space->getId()); |
|
38
|
|
|
if (!$entity) { |
|
39
|
|
|
$query = "return box.space.".$space->getName().".index[0]:max()"; |
|
40
|
|
|
$data = $this->mapper->getClient()->evaluate($query)->getData(); |
|
41
|
|
|
$max = $data ? $data[0][0] : 0; |
|
42
|
|
|
|
|
43
|
|
|
$entity = $this->mapper->create('sequence', [ |
|
44
|
|
|
'space' => $space->getId(), |
|
45
|
|
|
'counter' => $max, |
|
46
|
|
|
]); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
$this->mapper->getSchema()->getSpace('sequence') |
|
50
|
|
|
->getRepository() |
|
51
|
|
|
->update($entity, [['+', 'counter', 1]]); |
|
52
|
|
|
|
|
53
|
|
|
return $entity->counter; |
|
54
|
|
|
} |
|
55
|
|
|
} |
|
56
|
|
|
|
This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.
Both the
$myVarassignment in line 1 and the$higherassignment in line 2 are dead. The first because$myVaris never used and the second because$higheris always overwritten for every possible time line.