Test Failed
Branch master (e46a7e)
by mcfog
02:27
created

AttachToRequestTrait   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 1
dl 0
loc 41
ccs 0
cts 13
cp 0
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A fromRequest() 0 13 4
A attachToRequest() 0 16 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Lit\Nimo\Traits;
6
7
use Psr\Http\Message\ServerRequestInterface;
8
9
trait AttachToRequestTrait
10
{
11
    /**
12
     * @param ServerRequestInterface $request
13
     * @return static
14
     */
15
    public static function fromRequest(ServerRequestInterface $request)
16
    {
17
        /** @noinspection PhpUndefinedClassConstantInspection */
18
        $key = defined('static::ATTR_KEY') ? static::ATTR_KEY : static::class;
19
        if (!$instance = $request->getAttribute($key)) {
20
            throw new \RuntimeException('middleware not found:' . $key);
21
        }
22
        if (!$instance instanceof static) {
23
            throw new \RuntimeException('middleware class error:' . $key);
24
        }
25
26
        return $instance;
27
    }
28
29
    /**
30
     * @param ServerRequestInterface $request
31
     * @return ServerRequestInterface
32
     */
33
    protected function attachToRequest(ServerRequestInterface $request = null): ServerRequestInterface
34
    {
35
        /**
36
         * @var ServerRequestInterface $request
37
         */
38
        /** @noinspection PhpUndefinedFieldInspection */
39
        $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...
40
41
        /** @noinspection PhpUndefinedClassConstantInspection */
42
        $key = defined('static::ATTR_KEY') ? static::ATTR_KEY : static::class;
43
        if ($request->getAttribute($key)) {
44
            throw new \RuntimeException('middleware collision:' . $key);
45
        }
46
47
        return $this->request = $request->withAttribute($key, $this);
48
    }
49
}
50