Completed
Push — master ( 440ed8...3092e4 )
by John
01:58
created

EntityManagedCachingEndpointFactory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
c 0
b 0
f 0
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 3
crap 1
1
<?php
2
namespace LunixRESTBasics\Endpoint;
3
4
use Doctrine\ORM\EntityManager;
5
use LunixREST\Endpoint\CachingEndpoint;
6
use LunixREST\Endpoint\CachingEndpointFactory;
7
use Psr\Cache\CacheItemPoolInterface;
8
use Psr\Log\LoggerInterface;
9
10
abstract class EntityManagedCachingEndpointFactory extends CachingEndpointFactory
11
{
12
    /**
13
     * @var EntityManager
14
     */
15
    protected $entityManager;
16
17 1
    public function __construct(EntityManager $entityManager, CacheItemPoolInterface $cachePool, LoggerInterface $logger)
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...
18
    {
19 1
        $this->entityManager = $entityManager;
20 1
        parent::__construct($cachePool,$logger);
21 1
    }
22
23 1
    protected function getCachingEndpoint(string $name, string $version): CachingEndpoint
24
    {
25 1
        $endpoint = $this->getEntityManagedCachingEndpoint($name, $version);
26 1
        $endpoint->setEntityManager($this->entityManager);
27 1
        return $endpoint;
28
    }
29
30
    protected abstract function getEntityManagedCachingEndpoint(string $name, string $version): EntityManagedCachingEndpoint;
0 ignored issues
show
Coding Style introduced by
The abstract declaration must precede the visibility declaration
Loading history...
31
}
32