EntityDeleteListener   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 91.3%

Importance

Changes 0
Metric Value
dl 0
loc 49
ccs 21
cts 23
cp 0.913
rs 10
c 0
b 0
f 0
wmc 5
lcom 1
cbo 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getSubscribedEvents() 0 6 1
A preSoftDelete() 0 26 3
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