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

RequestValidatorMiddleware::process()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 7
cts 7
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 3
nop 2
crap 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