Completed
Push — master ( 298ac7...0024da )
by Oleg
12:58
created

TokenResourceMiddleware::process()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 40
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 40
ccs 0
cts 39
cp 0
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 30
nc 6
nop 2
crap 20
1
<?php
2
declare(strict_types=1);
3
4
namespace SlayerBirden\DataFlowServer\Authentication\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\Authentication\Entities\Token;
14
use SlayerBirden\DataFlowServer\Doctrine\Middleware\ResourceMiddlewareInterface;
15
use SlayerBirden\DataFlowServer\Notification\DangerMessage;
16
use Zend\Diactoros\Response\JsonResponse;
17
18
class TokenResourceMiddleware 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
42
        if ($id !== null) {
43
            try {
44
                $token = $this->entityManager->find(Token::class, $id);
45
                if ($token) {
46
                    return $handler->handle(
47
                        $request->withAttribute(self::DATA_RESOURCE, $token)
48
                    );
49
                } else {
50
                    return new JsonResponse([
51
                        'data' => [
52
                            'token' => null,
53
                        ],
54
                        'success' => false,
55
                        'msg' => new DangerMessage('Could not load Token by provided ID.'),
56
                    ], 404);
57
                }
58
            } catch (ORMInvalidArgumentException | ORMException $exception) {
59
                $this->logger->error((string)$exception);
60
                return new JsonResponse([
61
                    'data' => [
62
                        'token' => null,
63
                    ],
64
                    'success' => false,
65
                    'msg' => new DangerMessage('Error during loading Token.'),
66
                ], 404);
67
            }
68
        } else {
69
            return new JsonResponse([
70
                'data' => [
71
                    'token' => null,
72
                ],
73
                'success' => false,
74
                'msg' => new DangerMessage('No id provided.'),
75
            ], 404);
76
        }
77
    }
78
}
79