Completed
Push — master ( 4f4774...00e15e )
by Dmitry
02:49
created

Spy   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 78
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 14
lcom 1
cbo 2
dl 0
loc 78
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A beforeCreate() 0 4 1
A beforeUpdate() 0 7 2
A beforeRemove() 0 15 3
A reset() 0 6 1
A getKey() 0 11 2
A getChanges() 0 18 4
A hasChanges() 0 4 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 Spy extends Plugin
10
{
11
    private $created = [];
12
    private $updated = [];
13
    private $removed = [];
14
15
    public function beforeCreate(Entity $instance, Space $space)
16
    {
17
        $this->created[$this->getKey($instance, $space)] = $instance;
18
    }
19
20
    public function beforeUpdate(Entity $instance, Space $space)
21
    {
22
        $key = $this->getKey($instance, $space);
23
        if (!array_key_exists($key, $this->created)) {
24
            $this->updated[$key] = $instance;
25
        }
26
    }
27
28
    public function beforeRemove(Entity $instance, Space $space)
29
    {
30
        $key = $this->getKey($instance, $space);
31
32
        if (array_key_exists($key, $this->created)) {
33
            unset($this->created[$key]);
34
            return;
35
        }
36
37
        if (array_key_exists($key, $this->updated)) {
38
            unset($this->updated[$key]);
39
        }
40
41
        $this->removed[$key] = $instance;
42
    }
43
44
    public function reset()
45
    {
46
        $this->created = [];
47
        $this->updated = [];
48
        $this->removed = [];
49
    }
50
51
    private function getKey(Entity $instance, Space $space)
52
    {
53
        $key = [$space->getName()];
54
55
        $format = $space->getFormat();
56
        foreach ($space->getPrimaryIndex()->parts as $part) {
57
            $key[] = $instance->{$format[$part[0]]['name']};
58
        }
59
60
        return implode(':', $key);
61
    }
62
63
    public function getChanges()
64
    {
65
        $result = (object) [];
66
67
        foreach (['created', 'updated', 'removed'] as $action) {
68
            $data = [];
69
            foreach ($this->$action as $key => $row) {
70
                list($space) = explode(':', $key);
71
                if (!array_key_exists($space, $data)) {
72
                    $data[$space] = [];
73
                }
74
                $data[$space][] = $row;
75
            }
76
            $result->$action = $data;
77
        }
78
79
        return $result;
80
    }
81
82
    public function hasChanges()
83
    {
84
        return count($this->created) + count($this->updated) + count($this->removed) > 0;
85
    }
86
}
87