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 Spy extends Plugin |
10
|
|
|
{ |
11
|
|
|
private $create = []; |
12
|
|
|
private $update = []; |
13
|
|
|
private $remove = []; |
14
|
|
|
|
15
|
|
|
public function beforeCreate(Entity $instance, Space $space) |
16
|
|
|
{ |
17
|
|
|
$this->create[$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->create)) { |
24
|
|
|
$this->update[$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->create)) { |
33
|
|
|
unset($this->create[$key]); |
34
|
|
|
return; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
if(array_key_exists($key, $this->update)) { |
38
|
|
|
unset($this->update[$key]); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
$this->remove[$key] = $instance; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
public function reset() |
45
|
|
|
{ |
46
|
|
|
$this->create = []; |
47
|
|
|
$this->update = []; |
48
|
|
|
$this->remove = []; |
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
|
|
|
return (object) [ |
66
|
|
|
'create' => array_values($this->create), |
67
|
|
|
'update' => array_values($this->update), |
68
|
|
|
'remove' => array_values($this->remove), |
69
|
|
|
]; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
public function hasChanges() |
73
|
|
|
{ |
74
|
|
|
return count($this->create) + count($this->update) + count($this->remove) > 0; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|