|
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
|
|
|
* @param mixed|null $default |
|
36
|
|
|
* |
|
37
|
|
|
* @return mixed|null |
|
38
|
|
|
*/ |
|
39
|
|
|
private static function getAttribute(ServerRequestInterface $request, $name, $default = null) |
|
40
|
|
|
{ |
|
41
|
|
|
$attributes = $request->getAttribute(Middleware::KEY, []); |
|
42
|
|
|
|
|
43
|
|
|
if (isset($attributes[$name])) { |
|
44
|
|
|
return $attributes[$name]; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
return $default; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* Check whether an attribute exists. |
|
52
|
|
|
* |
|
53
|
|
|
* @param ServerRequestInterface $request |
|
54
|
|
|
* @param string $name |
|
55
|
|
|
* |
|
56
|
|
|
* @return bool |
|
57
|
|
|
*/ |
|
58
|
|
|
private static function hasAttribute(ServerRequestInterface $request, $name) |
|
59
|
|
|
{ |
|
60
|
|
|
$attributes = $request->getAttribute(Middleware::KEY); |
|
61
|
|
|
|
|
62
|
|
|
if (empty($attributes)) { |
|
63
|
|
|
return false; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
return array_key_exists($name, $attributes); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|