ActivePasswordMiddleware   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 7
dl 0
loc 38
ccs 15
cts 15
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A process() 0 11 2
A hasActivePassword() 0 10 1
1
<?php
2
declare(strict_types=1);
3
4
namespace SlayerBirden\DataFlowServer\Authentication\Middleware;
5
6
use Doctrine\Common\Collections\Criteria;
7
use Doctrine\Common\Collections\Selectable;
8
use Psr\Http\Message\ResponseInterface;
9
use Psr\Http\Message\ServerRequestInterface;
10
use Psr\Http\Server\MiddlewareInterface;
11
use Psr\Http\Server\RequestHandlerInterface;
12
use SlayerBirden\DataFlowServer\Domain\Entities\User;
13
use SlayerBirden\DataFlowServer\Stdlib\ResponseFactory;
14
15
final class ActivePasswordMiddleware implements MiddlewareInterface
16
{
17
    /**
18
     * @var Selectable
19
     */
20
    private $passwordRepository;
21
22 10
    public function __construct(Selectable $passwordRepository)
23
    {
24 10
        $this->passwordRepository = $passwordRepository;
25 10
    }
26
27
    /**
28
     * @inheritdoc
29
     */
30 10
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
31
    {
32 10
        $user = $request->getAttribute(TokenMiddleware::USER_PARAM);
33
34 10
        if ($this->hasActivePassword($user)) {
35 2
            $msg = 'You already have an active password. Please use "update" routine.';
36 2
            return (new ResponseFactory())($msg, 412, 'password');
37
        }
38
39 8
        return $handler->handle($request);
40
    }
41
42 10
    private function hasActivePassword(User $user): bool
43
    {
44 10
        $collection = $this->passwordRepository->matching(
45 10
            Criteria::create()
46 10
                ->where(Criteria::expr()->eq('owner', $user))
47 10
                ->andWhere(Criteria::expr()->eq('active', true))
48
        );
49
50 10
        return !$collection->isEmpty();
51
    }
52
}
53