1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace DoS\UserBundle\EventListener; |
4
|
|
|
|
5
|
|
|
use Doctrine\ORM\Event\OnFlushEventArgs; |
6
|
|
|
use DoS\UserBundle\Security\Security; |
7
|
|
|
use DoS\UserBundle\Model\UserUpdaterAwareInterface; |
8
|
|
|
use DoS\UserBundle\Model\UserInterface; |
9
|
|
|
use Sylius\Component\User\Model\UserAwareInterface; |
10
|
|
|
|
11
|
|
|
class UserAwareResourceListener |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var Security |
15
|
|
|
*/ |
16
|
|
|
protected $security; |
17
|
|
|
|
18
|
|
|
public function __construct(Security $security) |
19
|
|
|
{ |
20
|
|
|
$this->security = $security; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param OnFlushEventArgs $onFlushEventArgs |
25
|
|
|
*/ |
26
|
|
|
public function onFlush(OnFlushEventArgs $onFlushEventArgs) |
27
|
|
|
{ |
28
|
|
|
$entityManager = $onFlushEventArgs->getEntityManager(); |
29
|
|
|
$unitOfWork = $entityManager->getUnitOfWork(); |
30
|
|
|
|
31
|
|
|
$entities = array_merge( |
32
|
|
|
$unitOfWork->getScheduledEntityInsertions(), |
33
|
|
|
$unitOfWork->getScheduledEntityUpdates() |
34
|
|
|
); |
35
|
|
|
|
36
|
|
|
foreach ($entities as $entity) { |
37
|
|
|
if (!$entity instanceof UserAwareInterface && !$entity instanceof UserUpdaterAwareInterface) { |
38
|
|
|
continue; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
if ($entity instanceof UserAwareInterface && !$entity->getUser()) { |
42
|
|
|
$entity->setUser($this->getUser()); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
if ($entity instanceof UserUpdaterAwareInterface && !$entity->getUpdater()) { |
46
|
|
|
$entity->setUpdater($this->getUser()); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
$entityManager->persist($entity); |
50
|
|
|
$metadata = $entityManager->getClassMetadata(get_class($entity)); |
51
|
|
|
$unitOfWork->recomputeSingleEntityChangeSet($metadata, $entity); |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @return UserInterface|null |
57
|
|
|
*/ |
58
|
|
|
private function getUser() |
59
|
|
|
{ |
60
|
|
|
return $this->security->getUser(); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|