Passed
Push — master ( b6a195...1e79f7 )
by mcfog
03:21
created

AttachToRequestTrait   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 10
eloc 17
dl 0
loc 40
ccs 0
cts 18
cp 0
rs 10
c 0
b 0
f 0

2 Methods

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