Passed
Push — master ( b3f945...fcf496 )
by Jelmer
04:58
created

RequestValidatorMiddleware   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 3
dl 0
loc 28
ccs 10
cts 10
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A process() 0 17 3
1
<?php declare(strict_types = 1);
2
3
namespace jschreuder\Middle\ServerMiddleware;
4
5
use Interop\Http\ServerMiddleware\DelegateInterface;
6
use Interop\Http\ServerMiddleware\MiddlewareInterface;
7
use jschreuder\Middle\Controller\RequestValidatorInterface;
8
use jschreuder\Middle\Controller\ValidationFailedException;
9
use Psr\Http\Message\ResponseInterface;
10
use Psr\Http\Message\ServerRequestInterface;
11
12
final class RequestValidatorMiddleware implements MiddlewareInterface
13
{
14
    /** @var  callable */
15
    private $errorHandler;
16
17 4
    public function __construct(callable $errorHandler)
18
    {
19 4
        $this->errorHandler = $errorHandler;
20 4
    }
21
22 3
    public function process(ServerRequestInterface $request, DelegateInterface $delegate): ResponseInterface
23
    {
24 3
        $controller = $request->getAttribute('controller');
25
26 3
        if ($controller instanceof RequestValidatorInterface) {
27
            // Execute the request-validator from the controller
28
            try {
29 2
                $controller->validateRequest($request);
30 1
            } catch (ValidationFailedException $exception) {
31
                // Hand of to error-handler on failure
32 1
                return ($this->errorHandler)($request, $exception);
33
            }
34
        }
35
36
        // Filtered and validated (if applicable), let's continue on
37 2
        return $delegate->process($request);
38
    }
39
}
40