Completed
Push — master ( 33bc8d...136dfe )
by Dmitry
03:12 queued 15s
created

Sequence::initSchema()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Tarantool\Mapper\Plugin;
6
7
use Exception;
8
use Tarantool\Client\Schema\Operations;
9
use Tarantool\Mapper\Entity;
10
use Tarantool\Mapper\Plugin;
11
use Tarantool\Mapper\Procedure\CreateSequence;
12
use Tarantool\Mapper\Space;
13
14
class Sequence extends Plugin
15
{
16
    public function generateKey(Entity $instance, Space $space) : Entity
17
    {
18
        $primary = $space->getPrimaryIndex();
19
        if (count($primary['parts']) == 1) {
20
            $key = $space->getFormat()[$primary['parts'][0][0]]['name'];
21
            if (!property_exists($instance, $key) || is_null($instance->$key)) {
22
                $instance->$key = $this->generateValue($space);
23
            }
24
        }
25
26
        return $instance;
27
    }
28
29
    private $sequences = [];
30
31
    public function initializeSequence(Space $space)
32
    {
33
        if (!count($this->sequences)) {
34
            foreach ($this->mapper->find('_vsequence') as $sq) {
35
                $this->sequences[$sq->name] = true;
36
            }
37
        }
38
39
        $name = $space->getName();
40
41
        if (!array_key_exists($name, $this->sequences)) {
42
            $primaryIndex = $space->getIndexes()[0];
43
            if (count($primaryIndex['parts']) !== 1) {
44
                throw new Exception("Composite primary key");
45
            }
46
            $this->mapper
47
                ->getPlugin(Procedure::class)
48
                ->get(CreateSequence::class)
49
                ->execute($name, $primaryIndex['name'], $primaryIndex['parts'][0][0]+1);
50
51
            $this->mapper->getRepository('_vsequence')->flushCache();
52
53
            $this->sequences[$name] = true;
54
        }
55
    }
56
57
    private function generateValue(Space $space) : int
58
    {
59
        $this->initializeSequence($space);
60
61
        $next = $this->mapper->getClient()
62
            ->call('box.sequence.'.$space->getName().':next');
63
64
        return $next[0];
65
    }
66
}
67