1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App\EventListener; |
4
|
|
|
|
5
|
|
|
use Doctrine\ORM\Event\LifecycleEventArgs; |
6
|
|
|
use Doctrine\Common\EventSubscriber; |
7
|
|
|
use Gedmo\SoftDeleteable\SoftDeleteableListener; |
8
|
|
|
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; |
9
|
|
|
use Symfony\Component\Security\Core\Exception\AccessDeniedException; |
10
|
|
|
|
11
|
|
|
class EntityDeleteListener implements EventSubscriber |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var TokenStorageInterface |
15
|
|
|
*/ |
16
|
|
|
private $tokenStorage; |
17
|
|
|
|
18
|
48 |
|
public function __construct(TokenStorageInterface $tokenStorage) |
19
|
|
|
{ |
20
|
48 |
|
$this->tokenStorage = $tokenStorage; |
21
|
48 |
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @inheritDoc |
25
|
|
|
*/ |
26
|
48 |
|
public function getSubscribedEvents() |
27
|
|
|
{ |
28
|
|
|
return [ |
29
|
48 |
|
SoftDeleteableListener::PRE_SOFT_DELETE |
30
|
|
|
]; |
31
|
|
|
} |
32
|
|
|
|
33
|
9 |
|
public function preSoftDelete(LifecycleEventArgs $args) |
34
|
|
|
{ |
35
|
9 |
|
$token = $this->tokenStorage->getToken(); |
36
|
9 |
|
$object = $args->getEntity(); |
37
|
9 |
|
$om = $args->getEntityManager(); |
38
|
9 |
|
$uow = $om->getUnitOfWork(); |
39
|
|
|
|
40
|
9 |
|
if (!method_exists($object, 'setDeletedBy')) { |
41
|
|
|
return; |
42
|
|
|
} |
43
|
|
|
|
44
|
9 |
|
if (null == $token) { |
45
|
|
|
throw new AccessDeniedException('Only authorized users can delete entities'); |
46
|
|
|
} |
47
|
|
|
|
48
|
9 |
|
$meta = $om->getClassMetadata(get_class($object)); |
49
|
9 |
|
$reflProp = $meta->getReflectionProperty('deletedBy'); |
50
|
9 |
|
$oldValue = $reflProp->getValue($object); |
51
|
9 |
|
$reflProp->setValue($object, $token->getUser()->getUsername()); |
52
|
|
|
|
53
|
9 |
|
$om->persist($object); |
54
|
9 |
|
$uow->propertyChanged($object, 'deletedBy', $oldValue, $token->getUser()->getUsername()); |
55
|
9 |
|
$uow->scheduleExtraUpdate($object, array( |
56
|
9 |
|
'deletedBy' => array($oldValue, $token->getUser()->getUsername()), |
57
|
|
|
)); |
58
|
9 |
|
} |
59
|
|
|
} |
60
|
|
|
|