Test Failed
Push — master ( 6888f6...bb3a51 )
by Jelmer
03:25
created

FilterValidationMiddleware::execute()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 22
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
c 0
b 0
f 0
rs 8.9197
cc 4
eloc 10
nc 6
nop 1
1
<?php declare(strict_types = 1);
2
3
namespace jschreuder\Middle\Controller;
4
5
use jschreuder\Middle\ApplicationInterface;
6
use Psr\Http\Message\ResponseInterface;
7
use Psr\Http\Message\ServerRequestInterface;
8
9
class FilterValidationMiddleware implements ApplicationInterface
10
{
11
    /** @var  ApplicationInterface */
12
    private $application;
13
14
    /** @var  callable */
15
    private $errorHandler;
16
17
    public function __construct(ApplicationInterface $application, callable $errorHandler)
18
    {
19
        $this->application = $application;
20
        $this->errorHandler = $errorHandler;
21
    }
22
23
    public function execute(ServerRequestInterface $request) : ResponseInterface
24
    {
25
        $controller = $request->getAttribute('controller');
26
27
        if ($controller instanceof RequestFilterInterface) {
28
            // Execute the request-filter from the controller
29
            $request = $controller->filterRequest($request);
30
        }
31
32
        if ($controller instanceof RequestValidatorInterface) {
33
            // Execute the request-validator from the controller
34
            try {
35
                $controller->validateRequest($request);
36
            } catch (ValidationFailedException $exception) {
37
                // Hand of to error-handler on failure
38
                return ($this->errorHandler)($request, $exception);
39
            }
40
        }
41
42
        // Filtered and validated (if applicable), let's continue on
43
        return $this->application->execute($request);
44
    }
45
}
46