Passed
Push — master ( 3d4420...1c003d )
by mcfog
01:46
created

AttachToRequestTrait::attachToRequest()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 16
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 0
cts 6
cp 0
rs 9.2
c 0
b 0
f 0
cc 4
eloc 6
nc 8
nop 1
crap 20
1
<?php namespace Nimo\Traits;
2
3
use Psr\Http\Message\ServerRequestInterface;
4
5
trait AttachToRequestTrait
6
{
7
    /**
8
     * @param ServerRequestInterface $request
9
     * @return static
10
     */
11
    public static function fromRequest(ServerRequestInterface $request): self
12
    {
13
        /** @noinspection PhpUndefinedClassConstantInspection */
14
        $key = defined('static::ATTR_KEY') ? static::ATTR_KEY : static::class;
15
        if (!$instance = $request->getAttribute($key)) {
16
            throw new \RuntimeException('middleware not found:' . $key);
17
        }
18
        if (!$instance instanceof static) {
19
            throw new \RuntimeException('middleware class error:' . $key);
20
        }
21
22
        return $instance;
23
    }
24
25
    /**
26
     * @param ServerRequestInterface $request
27
     * @return ServerRequestInterface
28
     */
29
    protected function attachToRequest(ServerRequestInterface $request = null): ServerRequestInterface
30
    {
31
        /**
32
         * @var ServerRequestInterface $request
33
         */
34
        /** @noinspection PhpUndefinedFieldInspection */
35
        $request = $request ?: $this->request;
0 ignored issues
show
Bug introduced by
The property request does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
36
37
        /** @noinspection PhpUndefinedClassConstantInspection */
38
        $key = defined('static::ATTR_KEY') ? static::ATTR_KEY : static::class;
39
        if ($request->getAttribute($key)) {
40
            throw new \RuntimeException('middleware collision:' . $key);
41
        }
42
43
        return $this->request = $request->withAttribute($key, $this);
44
    }
45
}
46