TicketCounter::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
4
namespace ConferenceTools\Tickets\Finder;
5
6
7
use Doctrine\Common\Collections\ArrayCollection;
8
use Doctrine\Common\Collections\Collection;
9
use Doctrine\ORM\EntityManager;
10
use ConferenceTools\Tickets\Domain\Finder\TicketCounterInterface;
11
use ConferenceTools\Tickets\Domain\ReadModel\TicketCounts\TicketCounter as TicketCounterReadModel;
12
13
class TicketCounter implements TicketCounterInterface
14
{
15
    /**
16
     * @var EntityManager
17
     */
18
    private $em;
19
20
    public function __construct(EntityManager $em)
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...
21
    {
22
        $this->em = $em;
23
    }
24
25
    /**
26
     * @param \string[] ...$identifiers
27
     * @return TicketCounterReadModel[]
28
     */
29
    public function byTicketTypeIdentifiers(string ...$identifiers): Collection
30
    {
31
        $qb = $this->em->getRepository(TicketCounterReadModel::class)->createQueryBuilder('t', 't.ticketType.identifier');
32
        /** @var TicketCounter[] $tickets */
33
        return new ArrayCollection($qb->where($qb->expr()->in('t.ticketType.identifier', $identifiers))
34
            ->getQuery()->getResult());
35
    }
36
}