AttachToRequestTrait::fromRequest()   A
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 3
Bugs 1 Features 0
Metric Value
eloc 6
c 3
b 1
f 0
dl 0
loc 11
ccs 0
cts 7
cp 0
rs 10
cc 4
nc 6
nop 1
crap 20
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Lit\Nimo\Traits;
6
7
use Psr\Http\Message\ServerRequestInterface;
8
9
/**
10
 * A common pattern that an object write itself to PSR request attributes.
11
 * By default the key will be the class name, can be override with class const `ATTR_KEY`.
12
 *
13
 * @property ServerRequestInterface $request
14
 */
15
trait AttachToRequestTrait
16
{
17
    /**
18
     * Get self from request (attributes).
19
     *
20
     * @param ServerRequestInterface $request The request.
21
     * @return static
22
     */
23
    public static function fromRequest(ServerRequestInterface $request)
24
    {
25
        $key = defined('static::ATTR_KEY') ? constant('static::ATTR_KEY') : static::class;
26
        if (!$instance = $request->getAttribute($key)) {
27
            throw new \RuntimeException('attribute empty:' . $key);
28
        }
29
        if (!$instance instanceof static) {
30
            throw new \RuntimeException('instance error:' . $key);
31
        }
32
33
        return $instance;
34
    }
35
36
    /**
37
     * Attach self to the request (in attributes) and return the new one.
38
     *
39
     * @param ServerRequestInterface $request The request.
40
     * @return ServerRequestInterface
41
     */
42
    protected function attachToRequest(ServerRequestInterface $request = null): ServerRequestInterface
43
    {
44
        if (property_exists($this, 'request')) {
45
            $request = $request ?: $this->request;
46
        }
47
        assert($request instanceof ServerRequestInterface);
48
49
        $key = defined('static::ATTR_KEY') ? constant('static::ATTR_KEY') : static::class;
50
        if ($request->getAttribute($key)) {
51
            throw new \RuntimeException('attribute collision:' . $key);
52
        }
53
54
        $request = $request->withAttribute($key, $this);
55
        if (property_exists($this, 'request')) {
56
            $this->request = $request;
57
        }
58
        return $request;
59
    }
60
}
61