|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Psr7Middlewares\Utils; |
|
4
|
|
|
|
|
5
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
6
|
|
|
use Psr7Middlewares\Middleware; |
|
7
|
|
|
use RuntimeException; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Trait to save middleware related things in the current session. |
|
11
|
|
|
*/ |
|
12
|
|
|
trait StorageTrait |
|
13
|
|
|
{ |
|
14
|
|
|
use AttributeTrait; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* Init the storage array. |
|
18
|
|
|
* |
|
19
|
|
|
* @param ServerRequestInterface $request |
|
20
|
|
|
* @param array $storage |
|
21
|
|
|
* |
|
22
|
|
|
* @return ServerRequestInterface |
|
23
|
|
|
*/ |
|
24
|
|
|
private static function initStorage(ServerRequestInterface $request, array $storage) |
|
25
|
|
|
{ |
|
26
|
|
|
return self::setAttribute($request, Middleware::STORAGE_KEY, $storage); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* Returns the value of a storage array. |
|
31
|
|
|
* |
|
32
|
|
|
* @param ServerRequestInterface $request |
|
33
|
|
|
* @param string|null $key |
|
34
|
|
|
* |
|
35
|
|
|
* @return mixed |
|
36
|
|
|
*/ |
|
37
|
|
|
private static function getStorage(ServerRequestInterface $request, $key = null) |
|
38
|
|
|
{ |
|
39
|
|
|
if (!self::hasAttribute($request, Middleware::STORAGE_KEY)) { |
|
40
|
|
|
throw new RuntimeException('No session storage initialized'); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
$storage = self::getAttribute($request, Middleware::STORAGE_KEY); |
|
44
|
|
|
|
|
45
|
|
|
if ($key === null) { |
|
46
|
|
|
return $storage; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
return isset($storage[$key]) ? $storage[$key] : null; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* Returns the value of a storage array. |
|
54
|
|
|
* |
|
55
|
|
|
* @param ServerRequestInterface $request |
|
56
|
|
|
* @param string $key |
|
57
|
|
|
* @param mixed $value |
|
58
|
|
|
* |
|
59
|
|
|
* @return ServerRequestInterface |
|
60
|
|
|
*/ |
|
61
|
|
|
private static function setStorage(ServerRequestInterface $request, $key, $value) |
|
62
|
|
|
{ |
|
63
|
|
|
if (!self::hasAttribute($request, Middleware::STORAGE_KEY)) { |
|
64
|
|
|
throw new RuntimeException('No session storage initialized'); |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
$storage = self::getAttribute($request, Middleware::STORAGE_KEY); |
|
68
|
|
|
$storage[$key] = $value; |
|
69
|
|
|
|
|
70
|
|
|
return self::setAttribute($request, Middleware::STORAGE_KEY, $storage); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|