Passed
Push — master ( 1a23d8...36a2b2 )
by Hannes
01:53
created

DispatchingMiddleware   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 29
rs 10
c 0
b 0
f 0
wmc 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A process() 0 11 2
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace inroutephp\inroute\Runtime\Middleware;
6
7
use inroutephp\inroute\Runtime\EnvironmentInterface;
8
use inroutephp\inroute\Runtime\Exception\DispatchException;
9
use Psr\Http\Message\ServerRequestInterface;
10
use Psr\Http\Message\ResponseInterface;
11
use Psr\Http\Server\MiddlewareInterface;
12
use Psr\Http\Server\RequestHandlerInterface;
13
14
final class DispatchingMiddleware implements MiddlewareInterface
15
{
16
    /**
17
     * @var callable
18
     */
19
    private $target;
20
21
    /**
22
     * @var EnvironmentInterface
23
     */
24
    private $environment;
25
26
    public function __construct(callable $target, EnvironmentInterface $environment)
27
    {
28
        $this->target = $target;
29
        $this->environment = $environment;
30
    }
31
32
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
33
    {
34
        $response = ($this->target)($request, $this->environment);
35
36
        if (!$response instanceof ResponseInterface) {
37
            throw new DispatchException(
38
                'Dispatcher callable must return a ResponseInterface object. Found: ' . gettype($response)
39
            );
40
        }
41
42
        return $response;
43
    }
44
}
45