1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @author Gerard van Helden <[email protected]> |
4
|
|
|
* @copyright Zicht online <http://zicht.nl> |
5
|
|
|
*/ |
6
|
|
|
|
7
|
|
|
namespace Zicht\Bundle\UrlBundle\Aliasing\Doctrine; |
8
|
|
|
|
9
|
|
|
use Doctrine\ORM\Event\LifecycleEventArgs; |
10
|
|
|
use Doctrine\ORM\Events; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* This subscriber handles the creation of aliases |
14
|
|
|
*/ |
15
|
|
|
class CreateAliasSubscriber extends BaseSubscriber |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @var bool |
19
|
|
|
*/ |
20
|
|
|
private $isHandling = false; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var array |
24
|
|
|
*/ |
25
|
|
|
private $records = []; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @return array |
29
|
|
|
*/ |
30
|
|
|
public function getSubscribedEvents() |
31
|
|
|
{ |
32
|
|
|
if ($this->enabled) { |
33
|
|
|
return [ |
34
|
|
|
Events::postPersist, |
35
|
|
|
Events::postUpdate, |
36
|
|
|
Events::postFlush, |
37
|
|
|
]; |
38
|
|
|
} else { |
39
|
|
|
return []; |
40
|
|
|
} |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Add a entity to record list for postFlush processing. |
45
|
|
|
* |
46
|
|
|
* @param object $entity |
47
|
|
|
* @param array $action |
48
|
|
|
*/ |
49
|
|
|
protected function addRecord($entity, array $action = []) |
50
|
|
|
{ |
51
|
|
|
if ($entity instanceof $this->className) { |
52
|
|
|
if (false !== ($index = array_search($entity, array_column($this->records, 0), true))) { |
53
|
|
|
if (!in_array($this->records[$index], $action)) { |
54
|
|
|
$this->records[$index][] = $action; |
55
|
|
|
} |
56
|
|
|
} else { |
57
|
|
|
$this->records[] = [$entity, $action]; |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* Registers a record to be scheduled for aliasing |
64
|
|
|
* |
65
|
|
|
* @param LifecycleEventArgs $e |
66
|
|
|
* @return void |
67
|
|
|
*/ |
68
|
|
|
public function postPersist($e) |
69
|
|
|
{ |
70
|
|
|
$this->addRecord($e->getEntity(), ['ACTION_POST_PERSIST']); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
|
74
|
|
|
/** |
75
|
|
|
* Registers a record to be scheduled for aliasing |
76
|
|
|
* |
77
|
|
|
* @param LifecycleEventArgs $e |
78
|
|
|
* @return void |
79
|
|
|
*/ |
80
|
|
|
public function postUpdate($e) |
81
|
|
|
{ |
82
|
|
|
$this->addRecord($e->getEntity(), ['ACTION_POST_UPDATE']); |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
|
86
|
|
|
/** |
87
|
|
|
* Create the aliases |
88
|
|
|
* |
89
|
|
|
* @return void |
90
|
|
|
*/ |
91
|
|
|
public function postFlush() |
92
|
|
|
{ |
93
|
|
|
if (!$this->enabled || $this->isHandling) { |
94
|
|
|
return; |
95
|
|
|
} |
96
|
|
|
|
97
|
|
|
$this->isHandling = true; |
98
|
|
|
|
99
|
|
|
$aliaser = $this->container->get($this->aliaserServiceId); |
100
|
|
|
|
101
|
|
|
while (list($record, $action) = array_shift($this->records)) { |
102
|
|
|
$aliaser->createAlias($record, $action); |
103
|
|
|
} |
104
|
|
|
|
105
|
|
|
$this->isHandling = false; |
106
|
|
|
} |
107
|
|
|
} |
108
|
|
|
|