Completed
Push — master ( 2b82a4...1acfba )
by Oscar
02:59
created

AttributeTrait::hasAttribute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
rs 9.4285
cc 2
eloc 5
nc 2
nop 2
1
<?php
2
3
namespace Psr7Middlewares\Utils;
4
5
use Psr\Http\Message\ServerRequestInterface;
6
use Psr7Middlewares\Middleware;
7
8
/**
9
 * Trait to save middleware related things as request attributes.
10
 */
11
trait AttributeTrait
12
{
13
    /**
14
     * Store an attribute in the request.
15
     *
16
     * @param ServerRequestInterface $request
17
     * @param string                 $name
18
     * @param mixed                  $value
19
     *
20
     * @return ServerRequestInterface
21
     */
22
    private static function setAttribute(ServerRequestInterface $request, $name, $value)
23
    {
24
        $attributes = $request->getAttribute(Middleware::KEY, []);
25
        $attributes[$name] = $value;
26
27
        return $request->withAttribute(Middleware::KEY, $attributes);
28
    }
29
30
    /**
31
     * Retrieves an attribute from the request.
32
     *
33
     * @param ServerRequestInterface $request
34
     * @param string                 $name
35
     *
36
     * @return mixed
37
     */
38
    private static function getAttribute(ServerRequestInterface $request, $name)
39
    {
40
        $attributes = $request->getAttribute(Middleware::KEY);
41
42
        if (isset($attributes[$name])) {
43
            return $attributes[$name];
44
        }
45
    }
46
47
    /**
48
     * Check whether an attribute exists.
49
     *
50
     * @param ServerRequestInterface $request
51
     * @param string                 $name
52
     *
53
     * @return bool
54
     */
55
    private static function hasAttribute(ServerRequestInterface $request, $name)
56
    {
57
        $attributes = $request->getAttribute(Middleware::KEY);
58
59
        if (empty($attributes)) {
60
            return false;
61
        }
62
63
        return array_key_exists($name, $attributes);
64
    }
65
}
66