Completed
Push — master ( 3e8a03...43ff2c )
by Dmitry
02:19
created

Sequence::beforeCreate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 2
1
<?php
2
3
namespace Tarantool\Mapper\Plugins;
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)) {
17
                $instance->$key = $this->generateValue($space);
18
            }
19
        }
20
    }
21
22
    private function generateValue($space)
23
    {
24
        $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...
25
26
        if(!$this->mapper->getSchema()->hasSpace('sequence')) {
27
28
            $sequence = $this->mapper->getSchema()->createSpace('sequence');
29
            $sequence->addProperty('space', 'unsigned');
30
            $sequence->addProperty('counter', 'unsigned');
31
            $sequence->createIndex('space');
32
33
            $this->mapper->create('sequence', [
34
                'space' => $sequence->getId(),
35
                'counter' => 1
36
            ]);
37
        }
38
39
        $entity = $this->mapper->findOne('sequence', $space->getId());
40
        if(!$entity) {
41
            $entity = $this->mapper->create('sequence', [
42
                'space' => $space->getId(),
43
                'counter' => 0,
44
            ]);
45
        }
46
47
        $this->mapper->getSchema()->getSpace('sequence')
48
            ->getRepository()
49
            ->update($entity, [['+', 'counter', 1]]);
50
51
        return $entity->counter;
52
    }
53
}
54