Completed
Push — master ( 5c0b6f...5c71f2 )
by Oleg
10:16
created

InvalidateTokensAction::invalidate()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 44

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 5.0384

Importance

Changes 0
Metric Value
dl 0
loc 44
ccs 23
cts 26
cp 0.8846
rs 8.9048
c 0
b 0
f 0
cc 5
nc 8
nop 1
crap 5.0384
1
<?php
2
declare(strict_types=1);
3
4
namespace SlayerBirden\DataFlowServer\Authentication\Controller;
5
6
use Doctrine\Common\Collections\Criteria;
7
use Doctrine\Common\Collections\Selectable;
8
use Doctrine\Common\Persistence\ManagerRegistry;
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\Notification\DangerMessage;
16
use SlayerBirden\DataFlowServer\Notification\SuccessMessage;
17
use SlayerBirden\DataFlowServer\Stdlib\Validation\DataValidationResponseFactory;
18
use Zend\Diactoros\Response\JsonResponse;
19
use Zend\Hydrator\HydratorInterface;
20
21
final class InvalidateTokensAction implements MiddlewareInterface
22
{
23
    /**
24
     * @var LoggerInterface
25
     */
26
    private $logger;
27
    /**
28
     * @var HydratorInterface
29
     */
30
    private $hydrator;
31
    /**
32
     * @var ManagerRegistry
33
     */
34
    private $managerRegistry;
35
    /**
36
     * @var Selectable
37
     */
38
    private $tokenRepository;
39
    /**
40
     * @var Selectable
41
     */
42
    private $userRepository;
43
44 3
    public function __construct(
45
        ManagerRegistry $managerRegistry,
46
        Selectable $tokenRepository,
47
        Selectable $userRepository,
48
        LoggerInterface $logger,
49
        HydratorInterface $hydrator
50
    ) {
51 3
        $this->managerRegistry = $managerRegistry;
52 3
        $this->tokenRepository = $tokenRepository;
53 3
        $this->userRepository = $userRepository;
54 3
        $this->logger = $logger;
55 3
        $this->hydrator = $hydrator;
56 3
    }
57
58
    /**
59
     * {@inheritdoc}
60
     */
61 3
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
62
    {
63 3
        $data = $request->getParsedBody();
64 3
        if (!is_array($data)) {
65
            return (new DataValidationResponseFactory())('tokens', []);
66
        }
67
68 3
        $users = $data['users'] ?? [];
69 3
        return $this->invalidate($users);
70
    }
71
72
    /**
73
     * @param array $users
74
     * @return ResponseInterface
75
     */
76 3
    private function invalidate(array $users = []): ResponseInterface
77
    {
78 3
        $criteria = Criteria::create();
79 3
        $criteria->where(Criteria::expr()->eq('active', true));
80 3
        if (!empty($users)) {
81 2
            $criteria->andWhere(Criteria::expr()->in('owner', $this->getUsers($users)));
82
        }
83
84 3
        $collection = $this->tokenRepository->matching($criteria);
85
86 3
        if ($collection->count() === 0) {
87 1
            return new JsonResponse([
88 1
                'data' => [
89
                    'count' => 0,
90
                    'tokens' => [],
91
                ],
92
                'success' => false,
93 1
                'msg' => new SuccessMessage('No tokens found to invalidate for given criteria.'),
94 1
            ], 400);
95
        }
96 2
        $em = $this->managerRegistry->getManagerForClass(Token::class);
97 2
        if ($em === null) {
98
            return new JsonResponse([
99
                'msg' => new DangerMessage('Could not retrieve ObjectManager'),
100
                'success' => false,
101
                'data' => [
102
                    'token' => null,
103
                ]
104
            ], 500);
105
        }
106 2
        foreach ($collection as $token) {
107 2
            $token->setActive(false);
108 2
            $em->persist($token);
109
        }
110 2
        $em->flush();
111 2
        return new JsonResponse([
112 2
            'data' => [
113 2
                'count' => $collection->count(),
114 2
                'tokens' => array_map([$this->hydrator, 'extract'], $collection->toArray()),
115
            ],
116
            'success' => true,
117 2
            'msg' => new SuccessMessage('Tokens have been deactivated.'),
118 2
        ], 200);
119
    }
120
121 2
    private function getUsers(array $users): array
122
    {
123 2
        $collection = $this->userRepository->matching(
124 2
            Criteria::create()->where(Criteria::expr()->in('id', $users))
125
        );
126 2
        return $collection->toArray();
127
    }
128
}
129