Completed
Push — master ( e3c0b5...539798 )
by Dmitry
03:14
created

Sequence::generateValue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 10
rs 9.4285
cc 1
eloc 6
nc 1
nop 1
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
    public function initializeSequence($space)
33
    {
34
        $this->initSchema();
35
36
        $spaceId = $space->getId();
0 ignored issues
show
Unused Code introduced by
$spaceId 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...
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
        return $entity;
50
    }
51
52
    private function generateValue($space)
53
    {
54
        $entity = $this->initializeSequence($space);
55
56
        $this->mapper->getSchema()->getSpace('sequence')
57
            ->getRepository()
58
            ->update($entity, [['+', 'counter', 1]]);
59
60
        return $entity->counter;
61
    }
62
}
63