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\TimestampEntity; |
12
|
|
|
use Starkerxp\StructureBundle\Entity\UtilisateurEntity; |
13
|
|
|
use Starkerxp\StructureBundle\Entity\UtilisateurInterface; |
14
|
|
|
|
15
|
|
|
// |
16
|
|
|
class EntitySubscriber implements EventSubscriber |
17
|
|
|
{ |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var UtilisateurInterface |
21
|
|
|
*/ |
22
|
|
|
protected $utilisateur; |
23
|
|
|
|
24
|
|
|
public function __construct($utilisateur) |
25
|
|
|
{ |
26
|
|
|
$this->utilisateur = $utilisateur; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function getSubscribedEvents() |
30
|
|
|
{ |
31
|
|
|
return [ |
32
|
|
|
'prePersist', |
33
|
|
|
'onFlush', |
34
|
|
|
]; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function prePersist(LifecycleEventArgs $args) |
38
|
|
|
{ |
39
|
|
|
$entity = $args->getEntity(); |
40
|
|
|
|
41
|
|
|
if ($entity instanceof TimestampEntity && empty($entity->getCreatedAt())) { |
42
|
|
|
$entity->setCreatedAt(new DateTime()); |
43
|
|
|
} |
44
|
|
|
if ($entity instanceof Entity && empty($entity->getUuid())) { |
45
|
|
|
$uuid = Uuid::uuid4(); |
46
|
|
|
$entity->setUuid($uuid); |
|
|
|
|
47
|
|
|
} |
48
|
|
|
if (!$entity instanceof UtilisateurEntity) { |
49
|
|
|
return false; |
50
|
|
|
} |
51
|
|
|
if (empty($entity->getUtilisateur())) { |
52
|
|
|
$entity->setUtilisateur($this->utilisateur); |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
|
57
|
|
|
public function onFlush(OnFlushEventArgs $event) |
58
|
|
|
{ |
59
|
|
|
$entityManager = $event->getEntityManager(); |
60
|
|
|
$uow = $entityManager->getUnitOfWork(); |
61
|
|
|
foreach ($uow->getScheduledEntityUpdates() as $entity) { |
62
|
|
|
if ($entity instanceof TimestampEntity) { |
63
|
|
|
$entity->setUpdatedAt(new DateTime()); |
64
|
|
|
} |
65
|
|
|
if ($entity instanceof Entity && empty($entity->getUuid())) { |
66
|
|
|
$uuid = Uuid::uuid4(); |
67
|
|
|
$entity->setUuid($uuid); |
|
|
|
|
68
|
|
|
} |
69
|
|
|
if (!$entity instanceof UtilisateurEntity) { |
70
|
|
|
continue; |
71
|
|
|
} |
72
|
|
|
if (empty($entity->getUtilisateur())) { |
73
|
|
|
$entity->setUtilisateur($this->utilisateur); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
} |
|
|
|
|
79
|
|
|
|
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: