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

BaseResourceMiddleware::process()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 40
ccs 12
cts 24
cp 0.5
rs 9.28
c 0
b 0
f 0
cc 4
nc 6
nop 2
crap 6
1
<?php
2
declare(strict_types=1);
3
4
namespace SlayerBirden\DataFlowServer\Doctrine\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\Notification\DangerMessage;
14
use Zend\Diactoros\Response\JsonResponse;
15
16
class BaseResourceMiddleware implements ResourceMiddlewareInterface
17
{
18
    /**
19
     * @var EntityManager
20
     */
21
    private $entityManager;
22
    /**
23
     * @var LoggerInterface
24
     */
25
    private $logger;
26
    /**
27
     * @var string
28
     */
29
    private $entityName;
30
    /**
31
     * @var string
32
     */
33
    private $dataObjectName;
34
    /**
35
     * @var string
36
     */
37
    private $idAttributeName;
38
39 28
    public function __construct(
40
        EntityManager $entityManager,
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...
41
        LoggerInterface $logger,
42
        string $entityName,
43
        string $dataObjectName,
44
        string $idAttributeName = 'id'
45
    ) {
46 28
        $this->entityManager = $entityManager;
47 28
        $this->logger = $logger;
48 28
        $this->entityName = $entityName;
49 28
        $this->dataObjectName = $dataObjectName;
50 28
        $this->idAttributeName = $idAttributeName;
51 28
    }
52
53
    /**
54
     * @inheritdoc
55
     */
56 28
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
57
    {
58 28
        $id = $request->getAttribute($this->idAttributeName);
59
60 28
        if ($id !== null) {
61
            try {
62 28
                $entity = $this->entityManager->find($this->entityName, $id);
63 28
                if ($entity) {
64 20
                    return $handler->handle(
65 20
                        $request->withAttribute(self::DATA_RESOURCE, $entity)
66
                    );
67
                } else {
68 8
                    return new JsonResponse([
69 8
                        'data' => [
70 8
                            $this->dataObjectName => null,
71
                        ],
72
                        'success' => false,
73 8
                        'msg' => new DangerMessage(sprintf('Could not load %s by provided ID.', $this->dataObjectName)),
74 8
                    ], 404);
75
                }
76
            } catch (ORMInvalidArgumentException | ORMException $exception) {
77
                $this->logger->error((string)$exception);
78
                return new JsonResponse([
79
                    'data' => [
80
                        $this->dataObjectName => null,
81
                    ],
82
                    'success' => false,
83
                    'msg' => new DangerMessage(sprintf('Error during loading %s.', $this->dataObjectName)),
84
                ], 500);
85
            }
86
        } else {
87
            return new JsonResponse([
88
                'data' => [
89
                    $this->dataObjectName => null,
90
                ],
91
                'success' => false,
92
                'msg' => new DangerMessage(sprintf('No %s provided.', $this->idAttributeName)),
93
            ], 400);
94
        }
95
    }
96
}
97