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

InvalidateTokensAction::process()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 28
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 28
ccs 0
cts 26
cp 0
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 22
nc 6
nop 2
crap 20
1
<?php
2
declare(strict_types=1);
3
4
namespace SlayerBirden\DataFlowServer\Authentication\Controller;
5
6
use Doctrine\Common\Collections\Criteria;
7
use Doctrine\ORM\EntityManager;
8
use Doctrine\ORM\ORMException;
9
use Psr\Http\Message\ResponseInterface;
10
use Psr\Http\Message\ServerRequestInterface;
11
use Psr\Http\Server\MiddlewareInterface;
12
use Psr\Http\Server\RequestHandlerInterface;
13
use Psr\Log\LoggerInterface;
14
use SlayerBirden\DataFlowServer\Authentication\Entities\Token;
15
use SlayerBirden\DataFlowServer\Domain\Entities\User;
16
use SlayerBirden\DataFlowServer\Notification\DangerMessage;
17
use SlayerBirden\DataFlowServer\Notification\SuccessMessage;
18
use Zend\Diactoros\Response\JsonResponse;
19
use Zend\Hydrator\ExtractionInterface;
20
21
class InvalidateTokensAction implements MiddlewareInterface
22
{
23
    /**
24
     * @var EntityManager
25
     */
26
    private $entityManager;
27
    /**
28
     * @var LoggerInterface
29
     */
30
    private $logger;
31
    /**
32
     * @var ExtractionInterface
33
     */
34
    private $extraction;
35
36
    public function __construct(EntityManager $entityManager, LoggerInterface $logger, ExtractionInterface $extraction)
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...
37
    {
38
        $this->entityManager = $entityManager;
39
        $this->logger = $logger;
40
        $this->extraction = $extraction;
41
    }
42
43
    /**
44
     * @inheritdoc
45
     */
46
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
47
    {
48
        $data = $request->getParsedBody();
49
50
        $users = $data['users'] ?? [];
51
        $all = $data['all'] ?? false;
52
53
        try {
54
            if ($all) {
55
                return $this->invalidateAll();
56
            } elseif (!empty($users)) {
57
                return $this->invalidateByUsers($users);
58
            } else {
59
                return new JsonResponse([
60
                    'data' => [],
61
                    'success' => false,
62
                    'msg' => new DangerMessage('Empty criteria provided.'),
63
                ], 400);
64
            }
65
        } catch (ORMException $exception) {
66
            $this->logger->error((string)$exception);
67
            return new JsonResponse([
68
                'data' => [],
69
                'success' => false,
70
                'msg' => new DangerMessage('There was an error while invalidating the tokens.'),
71
            ], 400);
72
        }
73
    }
74
75
    /**
76
     * @return ResponseInterface
77
     * @throws ORMException
78
     * @throws \Doctrine\ORM\OptimisticLockException
79
     */
80
    private function invalidateAll(): ResponseInterface
81
    {
82
        /** @var Token[] $collection */
83
        $collection = $this->entityManager->getRepository(Token::class)->findAll();
84
        foreach ($collection as $token) {
85
            $token->setActive(false);
86
            $this->entityManager->persist($token);
87
        }
88
89
        $this->entityManager->flush();
90
        return new JsonResponse([
91
            'data' => [
92
                'count' => count($collection),
93
            ],
94
            'success' => true,
95
            'msg' => new SuccessMessage('All tokens have been deactivated.'),
96
        ], 200);
97
    }
98
99
    /**
100
     * @param array $users
101
     * @return ResponseInterface
102
     * @throws ORMException
103
     * @throws \Doctrine\ORM\OptimisticLockException
104
     */
105
    private function invalidateByUsers(array $users): ResponseInterface
106
    {
107
        $collection = $this->entityManager
108
            ->getRepository(Token::class)
109
            ->matching(
110
                Criteria::create()->where(Criteria::expr()->in('user', $this->getUsers($users)))
111
            );
112
        foreach ($collection as $token) {
113
            $token->setActive(false);
114
            $this->entityManager->persist($token);
115
        }
116
        $this->entityManager->flush();
117
        return new JsonResponse([
118
            'data' => [
119
                'count' => $collection->count(),
120
                'tokens' => array_map([$this->extraction, 'extract'], $collection->toArray()),
121
            ],
122
            'success' => true,
123
            'msg' => new SuccessMessage('Tokens have been deactivated.'),
124
        ], 200);
125
    }
126
127
    private function getUsers(array $users): array
128
    {
129
        $collection = $this->entityManager
130
            ->getRepository(User::class)
131
            ->matching(
132
                Criteria::create()->where(Criteria::expr()->in('id', $users))
133
            );
134
        return $collection->toArray();
135
    }
136
}
137