1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Psi\Component\ObjectAgent; |
4
|
|
|
|
5
|
|
|
use Psi\Component\ObjectAgent\Event\ObjectEvent; |
6
|
|
|
use Psi\Component\ObjectAgent\Query\Query; |
7
|
|
|
use Symfony\Component\EventDispatcher\EventDispatcherInterface; |
8
|
|
|
use Psi\Component\ObjectAgent\Capabilities; |
9
|
|
|
|
10
|
|
|
class EventDispatchingAgent implements AgentInterface |
11
|
|
|
{ |
12
|
|
|
private $dispatcher; |
13
|
|
|
private $agent; |
14
|
|
|
|
15
|
|
|
public function __construct( |
16
|
|
|
AgentInterface $agent, |
17
|
|
|
EventDispatcherInterface $dispatcher |
18
|
|
|
) { |
19
|
|
|
$this->agent = $agent; |
20
|
|
|
$this->dispatcher = $dispatcher; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* {@inheritdoc} |
25
|
|
|
*/ |
26
|
|
|
public function getCapabilities(): Capabilities |
27
|
|
|
{ |
28
|
|
|
return $this->agnet->getCapabilities(); |
|
|
|
|
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* {@inheritdoc} |
33
|
|
|
*/ |
34
|
|
|
public function find($identifier, string $class = null) |
35
|
|
|
{ |
36
|
|
|
return $this->agent->find($identifier, $class); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* {@inheritdoc} |
41
|
|
|
*/ |
42
|
|
|
public function save($object) |
43
|
|
|
{ |
44
|
|
|
$this->dispatch(Events::PRE_SAVE, $object); |
45
|
|
|
$this->agent->save($object); |
46
|
|
|
$this->dispatch(Events::POST_SAVE, $object); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* {@inheritdoc} |
51
|
|
|
*/ |
52
|
|
|
public function query(Query $query): \Traversable |
53
|
|
|
{ |
54
|
|
|
return $this->agent->query($query); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* {@inheritdoc} |
59
|
|
|
*/ |
60
|
|
|
public function delete($object) |
61
|
|
|
{ |
62
|
|
|
$this->dispatch(Events::PRE_DELETE, $object); |
63
|
|
|
$this->agent->delete($object); |
64
|
|
|
$this->dispatch(Events::POST_DELETE, $object); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* {@inheritdoc} |
69
|
|
|
*/ |
70
|
|
|
public function getIdentifier($object) |
71
|
|
|
{ |
72
|
|
|
return $this->agent->getIdentifier($object); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* {@inheritdoc} |
77
|
|
|
*/ |
78
|
|
|
public function supports(string $class): bool |
79
|
|
|
{ |
80
|
|
|
return $this->agent->supports($class); |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
/** |
84
|
|
|
* {@inheritdoc} |
85
|
|
|
*/ |
86
|
|
|
public function setParent($object, $parent) |
87
|
|
|
{ |
88
|
|
|
return $this->agent->setParent($object, $parent); |
89
|
|
|
} |
90
|
|
|
|
91
|
|
|
private function dispatch(string $eventName, $object) |
92
|
|
|
{ |
93
|
|
|
$this->dispatcher->dispatch($eventName, new ObjectEvent($this->agent, $object)); |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: