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

ValidateOwnerMiddleware   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 26
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 6

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 6
dl 0
loc 26
ccs 11
cts 11
cp 1
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A process() 0 20 5
1
<?php
2
declare(strict_types=1);
3
4
namespace SlayerBirden\DataFlowServer\Domain\Middleware;
5
6
use Psr\Http\Message\ResponseInterface;
7
use Psr\Http\Message\ServerRequestInterface;
8
use Psr\Http\Server\MiddlewareInterface;
9
use Psr\Http\Server\RequestHandlerInterface;
10
use SlayerBirden\DataFlowServer\Authentication\Middleware\TokenMiddleware;
11
use SlayerBirden\DataFlowServer\Doctrine\Middleware\ResourceMiddlewareInterface;
12
use SlayerBirden\DataFlowServer\Domain\Entities\ClaimedResourceInterface;
13
use SlayerBirden\DataFlowServer\Domain\Entities\User;
14
use SlayerBirden\DataFlowServer\Notification\DangerMessage;
15
use Zend\Diactoros\Response\JsonResponse;
16
17
class ValidateOwnerMiddleware implements MiddlewareInterface
18
{
19
    /**
20
     * @inheritdoc
21
     */
22 10
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
23
    {
24 10
        $resource = $request->getAttribute(ResourceMiddlewareInterface::DATA_RESOURCE);
25
26 10
        if ($resource && $resource instanceof ClaimedResourceInterface) {
27 5
            $resourceOwner = $resource->getOwner();
28
            /** @var User|null $currentOwner */
29 5
            $currentOwner = $request->getAttribute(TokenMiddleware::USER_PARAM);
30
31 5
            if (!$currentOwner || ($currentOwner->getId() !== $resourceOwner->getId())) {
32 1
                return new JsonResponse([
33 1
                    'data' => [],
34 1
                    'msg' => new DangerMessage('Access denied.'),
35
                    'success' => false
36 1
                ], 403);
37
            }
38
        }
39
40 9
        return $handler->handle($request);
41
    }
42
}
43