TerminateEventListener::handle()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Webhook\Bundle\EventListener;
6
7
use Doctrine\ORM\EntityManager;
8
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
9
use Symfony\Component\HttpKernel\Event\PostResponseEvent;
10
use Symfony\Component\HttpKernel\KernelEvents;
11
12
final class TerminateEventListener implements EventSubscriberInterface
13
{
14
    /** @var EntityManager */
15
    private $entityManager;
16
17
    /**
18
     * TerminateEventListener constructor.
19
     *
20
     * @param EntityManager $entityManager
21
     */
22
    public function __construct(EntityManager $entityManager)
0 ignored issues
show
Bug introduced by
You have injected the EntityManager via parameter $entityManager. 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...
23
    {
24
        $this->entityManager = $entityManager;
25
    }
26
27
    /**
28
     * @return array
29
     */
30
    public static function getSubscribedEvents(): array
31
    {
32
        return [
33
            KernelEvents::TERMINATE => 'handle',
34
        ];
35
    }
36
37
    /**
38
     * @param PostResponseEvent $event
39
     *
40
     * @throws \Doctrine\Common\Persistence\Mapping\MappingException
41
     */
42
    public function handle(PostResponseEvent $event): void
0 ignored issues
show
Unused Code introduced by
The parameter $event is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
43
    {
44
        $this->entityManager->clear();
45
    }
46
}
47