|
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
|
|
|
|