1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Phauthentic\Infrastructure\Http\Session\Middleware; |
6
|
|
|
|
7
|
|
|
use Phauthentic\Infrastructure\Http\Session\SessionInterface; |
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
9
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
10
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
11
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
12
|
|
|
use RuntimeException; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* PSR 15 Middleware |
16
|
|
|
*/ |
17
|
|
|
class SessionMiddleware implements MiddlewareInterface |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* Session Attribute in the request object |
21
|
|
|
* |
22
|
|
|
* @var string |
23
|
|
|
*/ |
24
|
|
|
protected $sessionAttribute = 'session'; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Session Object |
28
|
|
|
* |
29
|
|
|
* @var \Phauthentic\Infrastructure\Http\Session\SessionInterface |
30
|
|
|
*/ |
31
|
|
|
protected $session; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Constructor. |
35
|
|
|
* |
36
|
|
|
* @param \Phauthentic\Infrastructure\Http\Session\SessionInterface $session Session |
37
|
|
|
*/ |
38
|
|
|
public function __construct( |
39
|
|
|
SessionInterface $session |
40
|
|
|
) { |
41
|
|
|
$this->session = $session; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* Sets the identity attribute |
46
|
|
|
* |
47
|
|
|
* @param string $attribute Attribute name |
48
|
|
|
* @return $this |
49
|
|
|
*/ |
50
|
|
|
public function setSessionAttribute(string $attribute): self |
51
|
|
|
{ |
52
|
|
|
$this->sessionAttribute = $attribute; |
53
|
|
|
|
54
|
|
|
return $this; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Adds an attribute to the request and returns a modified request. |
59
|
|
|
* |
60
|
|
|
* @param ServerRequestInterface $request Request. |
61
|
|
|
* @param string $name Attribute name. |
62
|
|
|
* @param mixed $value Attribute value. |
63
|
|
|
* @return ServerRequestInterface |
64
|
|
|
* @throws RuntimeException When attribute is present. |
65
|
|
|
*/ |
66
|
|
|
protected function addAttribute(ServerRequestInterface $request, string $name, $value): ServerRequestInterface |
67
|
|
|
{ |
68
|
|
|
if ($request->getAttribute($name)) { |
69
|
|
|
throw new RuntimeException(sprintf( |
70
|
|
|
'Request attribute `%s` is already in use.', |
71
|
|
|
$name |
72
|
|
|
)); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
return $request->withAttribute($name, $value); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* {@inheritDoc} |
80
|
|
|
* |
81
|
|
|
* @throws RuntimeException When request attribute exists. |
82
|
|
|
*/ |
83
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
84
|
|
|
{ |
85
|
|
|
$request = $this->addAttribute( |
86
|
|
|
$request, |
87
|
|
|
$this->sessionAttribute, |
88
|
|
|
$this->session |
89
|
|
|
); |
90
|
|
|
|
91
|
|
|
return $handler->handle($request); |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|