AccessChecker::withPermission()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
ccs 0
cts 4
cp 0
crap 2
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Middleware;
6
7
use App\User\UserService;
8
use Psr\Http\Message\ResponseFactoryInterface;
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 Yiisoft\Http\Status;
14
15
final class AccessChecker implements MiddlewareInterface
16
{
17
    private ResponseFactoryInterface $responseFactory;
18
    private UserService $userService;
19
    private ?string $permission = null;
20
21
    public function __construct(
22
        ResponseFactoryInterface $responseFactory,
23
        UserService $userService
24
    ) {
25
        $this->responseFactory = $responseFactory;
26
        $this->userService = $userService;
27
    }
28
29
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
30
    {
31
        if ($this->permission === null) {
32
            throw new \InvalidArgumentException('Permission not set.');
33
        }
34
35
        if (!$this->userService->hasPermission($this->permission)) {
36
            return $this->responseFactory->createResponse(Status::FORBIDDEN);
37
        }
38
39
        return $handler->handle($request);
40
    }
41
42
    public function withPermission(string $permission): self
43
    {
44
        $new = clone $this;
45
        $new->permission = $permission;
46
        return $new;
47
    }
48
}
49