|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Starkerxp\StructureBundle\Listener; |
|
4
|
|
|
|
|
5
|
|
|
use DateTime; |
|
6
|
|
|
use Doctrine\Common\EventSubscriber; |
|
7
|
|
|
use Doctrine\ORM\Event\LifecycleEventArgs; |
|
8
|
|
|
use Doctrine\ORM\Event\OnFlushEventArgs; |
|
9
|
|
|
use Ramsey\Uuid\Uuid; |
|
10
|
|
|
use Starkerxp\StructureBundle\Entity\Entity; |
|
11
|
|
|
use Starkerxp\StructureBundle\Entity\UtilisateurInterface; |
|
12
|
|
|
|
|
13
|
|
|
// |
|
14
|
|
|
class EntitySubscriber implements EventSubscriber |
|
15
|
|
|
{ |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @var UtilisateurInterface |
|
19
|
|
|
*/ |
|
20
|
|
|
protected $utilisateur; |
|
21
|
|
|
|
|
22
|
|
|
public function __construct($utilisateur) |
|
23
|
|
|
{ |
|
24
|
|
|
$this->utilisateur = $utilisateur; |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
public function getSubscribedEvents() |
|
28
|
|
|
{ |
|
29
|
|
|
return [ |
|
30
|
|
|
'prePersist', |
|
31
|
|
|
'onFlush', |
|
32
|
|
|
]; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
public function prePersist(LifecycleEventArgs $args) |
|
36
|
|
|
{ |
|
37
|
|
|
$entity = $args->getEntity(); |
|
38
|
|
|
|
|
39
|
|
|
if (!$entity instanceof Entity) { |
|
40
|
|
|
return false; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
$this->traitement($entity); |
|
44
|
|
|
|
|
45
|
|
|
if (empty($entity->getCreatedAt())) { |
|
46
|
|
|
$entity->setCreatedAt(new DateTime()); |
|
47
|
|
|
} |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
private function traitement(Entity $entity) |
|
51
|
|
|
{ |
|
52
|
|
|
if (empty($entity->getUuid())) { |
|
53
|
|
|
$uid = Uuid::uuid4(); |
|
54
|
|
|
$entity->setUuid($uid); |
|
|
|
|
|
|
55
|
|
|
} |
|
56
|
|
|
if (empty($entity->getUtilisateur())) { |
|
|
|
|
|
|
57
|
|
|
$entity->setUtilisateur($this->utilisateur); |
|
|
|
|
|
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
public function onFlush(OnFlushEventArgs $event) |
|
62
|
|
|
{ |
|
63
|
|
|
$entityManager = $event->getEntityManager(); |
|
64
|
|
|
$uow = $entityManager->getUnitOfWork(); |
|
65
|
|
|
foreach ($uow->getScheduledEntityUpdates() as $entity) { |
|
66
|
|
|
if (!$entity instanceof Entity) { |
|
67
|
|
|
continue; |
|
68
|
|
|
} |
|
69
|
|
|
$this->traitement($entity); |
|
70
|
|
|
$entity->setUpdatedAt(new DateTime()); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
|
|
|
|
|
74
|
|
|
|
It seems like the type of the argument is not accepted by the function/method which you are calling.
In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.
We suggest to add an explicit type cast like in the following example: