Completed
Pull Request — master (#2743)
by Jeroen
14:54
created

SlugListener::dispatch()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 10
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 10
loc 10
c 0
b 0
f 0
ccs 0
cts 0
cp 0
rs 9.9332
cc 2
nc 2
nop 2
crap 6
1
<?php
2
3
namespace Kunstmaan\NodeBundle\EventListener;
4
5
use Doctrine\ORM\EntityManager;
6
use Kunstmaan\NodeBundle\Controller\SlugActionInterface;
7
use Kunstmaan\NodeBundle\Entity\NodeTranslation;
8
use Kunstmaan\NodeBundle\Event\Events;
9
use Kunstmaan\NodeBundle\Event\SlugSecurityEvent;
10
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
11
use Symfony\Component\EventDispatcher\LegacyEventDispatcherProxy;
12
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
13
use Symfony\Component\HttpKernel\Event\ControllerEvent;
14
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
15
16
class SlugListener
17
{
18
    /**
19
     * @var EntityManager
20
     */
21
    protected $em;
22
23
    /**
24
     * @var ControllerResolverInterface
25
     */
26
    protected $resolver;
27
28
    /**
29
     * @var EventDispatcherInterface
30
     */
31
    protected $eventDispatcher;
32
33
    /**
34
     * SlugListener constructor.
35
     *
36
     * @param EntityManager               $em
37
     * @param ControllerResolverInterface $resolver
38
     * @param EventDispatcherInterface    $eventDispatcher
39
     */
40
    public function __construct(EntityManager $em, ControllerResolverInterface $resolver, EventDispatcherInterface $eventDispatcher)
0 ignored issues
show
Bug introduced by
You have injected the EntityManager via parameter $em. This is generally not recommended as it might get closed and become unusable. Instead, it is recommended to inject the ManagerRegistry and retrieve the EntityManager via getManager() each time you need it.

The EntityManager might become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:

function someFunction(ManagerRegistry $registry) {
    $em = $registry->getManager();
    $em->getConnection()->beginTransaction();
    try {
        // Do something.
        $em->getConnection()->commit();
    } catch (\Exception $ex) {
        $em->getConnection()->rollback();
        $em->close();

        throw $ex;
    }
}

If that code throws an exception and the EntityManager is closed. Any other code which depends on the same instance of the EntityManager during this request will fail.

On the other hand, if you instead inject the ManagerRegistry, the getManager() method guarantees that you will always get a usable manager instance.

Loading history...
41
    {
42
        $this->em = $em;
43
        $this->resolver = $resolver;
44
        $this->eventDispatcher = $eventDispatcher;
45
    }
46
47
    /**
48
     * @param FilterControllerEvent|ControllerEvent $event
49
     *
50
     * @throws \Exception
51
     */
52
    public function onKernelController($event)
53
    {
54 View Code Duplication
        if (!$event instanceof FilterControllerEvent && !$event instanceof ControllerEvent) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
55
            throw new \InvalidArgumentException(\sprintf('Expected instance of type %s, %s given', \class_exists(ControllerEvent::class) ? ControllerEvent::class : FilterControllerEvent::class, \is_object($event) ? \get_class($event) : \gettype($event)));
56
        }
57
58
        $request = $event->getRequest();
59
60
        // Check if the event has a nodeTranslation, if not this method can be skipped
61
        if (!$request->attributes->has('_nodeTranslation')) {
62
            return;
63
        }
64
65
        $nodeTranslation = $request->attributes->get('_nodeTranslation');
66
        if (!($nodeTranslation instanceof NodeTranslation)) {
67
            throw new \Exception('Invalid _nodeTranslation value found in request attributes');
68
        }
69
        $entity = $nodeTranslation->getRef($this->em);
70
71
        // If the entity is an instance of the SlugActionInterface, change the controller
72
        if ($entity instanceof SlugActionInterface) {
73
            $request->attributes->set('_entity', $entity);
74
75
            // Do security check by firing an event that gets handled by the SlugSecurityListener
76
            $securityEvent = new SlugSecurityEvent();
77
            $securityEvent
78
                ->setNode($nodeTranslation->getNode())
79
                ->setEntity($entity)
80
                ->setRequest($request)
81
                ->setNodeTranslation($nodeTranslation);
82
83
            $this->dispatch($securityEvent, Events::SLUG_SECURITY);
84
85
            // Set the right controller
86
            $request->attributes->set('_controller', $entity->getControllerAction());
87
            $event->setController($this->resolver->getController($request));
0 ignored issues
show
Security Bug introduced by
It seems like $this->resolver->getController($request) targeting Symfony\Component\HttpKe...erface::getController() can also be of type false; however, Symfony\Component\HttpKe...rEvent::setController() does only seem to accept callable, did you maybe forget to handle an error condition?
Loading history...
88
        }
89
    }
90
91
    /**
92
     * @param object $event
93
     * @param string $eventName
94
     *
95
     * @return object
96
     */
97 View Code Duplication
    private function dispatch($event, string $eventName)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
98
    {
99
        if (class_exists(LegacyEventDispatcherProxy::class)) {
100
            $eventDispatcher = LegacyEventDispatcherProxy::decorate($this->eventDispatcher);
101
102
            return $eventDispatcher->dispatch($event, $eventName);
103
        }
104
105
        return $this->eventDispatcher->dispatch($eventName, $event);
106
    }
107
}
108