Completed
Push — master ( 178a08...5c0b6f )
by Oleg
05:22
created

DbConfigResourceMiddleware   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 6
dl 0
loc 48
ccs 0
cts 30
cp 0
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A process() 0 27 4
1
<?php
2
declare(strict_types=1);
3
4
namespace SlayerBirden\DataFlowServer\Db\Middleware;
5
6
use Doctrine\ORM\EntityManager;
7
use Doctrine\ORM\ORMException;
8
use Doctrine\ORM\ORMInvalidArgumentException;
9
use Psr\Http\Message\ResponseInterface;
10
use Psr\Http\Message\ServerRequestInterface;
11
use Psr\Http\Server\RequestHandlerInterface;
12
use Psr\Log\LoggerInterface;
13
use SlayerBirden\DataFlowServer\Db\Entities\DbConfiguration;
14
use SlayerBirden\DataFlowServer\Doctrine\Middleware\ResourceMiddlewareInterface;
15
use SlayerBirden\DataFlowServer\Notification\DangerMessage;
16
use Zend\Diactoros\Response\JsonResponse;
17
18
class DbConfigResourceMiddleware implements ResourceMiddlewareInterface
19
{
20
    /**
21
     * @var EntityManager
22
     */
23
    private $entityManager;
24
    /**
25
     * @var LoggerInterface
26
     */
27
    private $logger;
28
29
    public function __construct(EntityManager $entityManager, 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...
30
    {
31
        $this->entityManager = $entityManager;
32
        $this->logger = $logger;
33
    }
34
35
    /**
36
     * @inheritdoc
37
     */
38
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
39
    {
40
        $id = $request->getAttribute('id');
41
        $msg = new DangerMessage('Could not load Configuration by provided ID.');
42
43
        if ($id !== null) {
44
            try {
45
                $dbConfig = $this->entityManager->find(DbConfiguration::class, $id);
46
                if ($dbConfig) {
47
                    return $handler->handle(
48
                        $request->withAttribute(self::DATA_RESOURCE, $dbConfig)
49
                    );
50
                }
51
            } catch (ORMInvalidArgumentException | ORMException $exception) {
52
                $this->logger->error((string)$exception);
53
                $msg = new DangerMessage('Error during loading DB Configuration.');
54
            }
55
        }
56
57
        return new JsonResponse([
58
            'data' => [
59
                'configuration' => null,
60
            ],
61
            'success' => false,
62
            'msg' => $msg,
63
        ], 404);
64
    }
65
}
66