Passed
Push — master ( 863ad3...126876 )
by Enrico
02:01
created

Psr15Trait   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
eloc 15
dl 0
loc 42
c 0
b 0
f 0
ccs 16
cts 16
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A handle() 0 4 1
A registerAsMiddleware() 0 5 1
A handleRunner() 0 16 3
1
<?php
2
3
/*
4
 * This file is part of the uSilex framework.
5
 *
6
 * (c) Enrico Fagnoni <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace uSilex\Pimple;
13
14
use Psr\Http\Server\RequestHandlerInterface;
15
use Psr\Http\Server\MiddlewareInterface;
16
use Psr\Http\Message\ServerRequestInterface;
17
use Psr\Http\Message\ResponseInterface;
18
use OutOfBoundsException;
19
use TypeError;
20
21
/**
22
 * Psr15 trait. HTTP Server Request Handlers implementation
23
 *
24
 * @author Enrico Fagnoni <[email protected]>
25
 */
26
trait Psr15Trait
27
{
28
    
29
    protected $middlewares = [];
30
    
31
    
32 4
    public function registerAsMiddleware(string $servicename)
33
    {
34 4
        $this->middlewares[] = $servicename;
35
        
36 4
        return $this;
37
    }
38
    
39
    
40 5
    protected function handleRunner(ServerRequestInterface $request) : ResponseInterface
41
    {
42 5
        $middlewareServiceName = current($this->middlewares);
43 5
        if (!$middlewareServiceName) {
44 1
            throw new OutOfBoundsException("No middleware to produce an http response");
45
        }
46 4
        $middleware = $this[$middlewareServiceName];
47 4
        if( !($middleware instanceof MiddlewareInterface)) {
48 1
            throw new TypeError("$middlewareServiceName is not a middleware");
49
        }
50 3
        next($this->middlewares);
51
        
52
        // execute middleware
53 3
        $result = $middleware->process($request, $this);
0 ignored issues
show
Bug introduced by
$this of type uSilex\Pimple\Psr15Trait is incompatible with the type Psr\Http\Server\RequestHandlerInterface expected by parameter $handler of Psr\Http\Server\MiddlewareInterface::process(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

53
        $result = $middleware->process($request, /** @scrutinizer ignore-type */ $this);
Loading history...
54
        
55 3
        return $result;
56
    }
57
    
58
    
59
    /**
60
     * Handles a request and produces a response
61
     *
62
     * May call other collaborating code to generate the response.
63
     */
64 5
    public function handle(ServerRequestInterface $request) : ResponseInterface
65
    {
66 5
        reset( $this->middlewares);
67 5
        return $this->handleRunner($request);
68
    }
69
    
70
}
71