Completed
Push — master ( 0668bb...e0da03 )
by Adrien
01:44
created

EntityID::getEntity()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace GraphQL\Doctrine\Definition;
6
7
use Doctrine\ORM\EntityManager;
8
use GraphQL\Error\Error;
9
10
/**
11
 * A object used to fetch the entity from DB on demand
12
 */
13
class EntityID
14
{
15
    /**
16
     * @var EntityManager
17
     */
18
    private $entityManager;
19
20
    /**
21
     * The entity class name
22
     *
23
     * @var string
24
     */
25
    private $className;
26
27
    /**
28
     * The entity id
29
     *
30
     * @var null|string
31
     */
32
    private $id;
33
34 4
    public function __construct(EntityManager $entityManager, string $className, ?string $id)
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...
35
    {
36 4
        $this->entityManager = $entityManager;
37 4
        $this->className = $className;
38 4
        $this->id = $id;
39 4
    }
40
41
    /**
42
     * Get the entity from DB
43
     *
44
     * @return mixed entity
45
     */
46 4
    public function getEntity()
47
    {
48 4
        $entity = $this->entityManager->getRepository($this->className)->find($this->id);
49 4
        if (!$entity) {
50 2
            throw new Error('Entity not found for class `' . $this->className . '` and ID `' . $this->id . '`');
51
        }
52
53 2
        return $entity;
54
    }
55
}
56