1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Spiral\Bootloader\Http; |
6
|
|
|
|
7
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
8
|
|
|
use Spiral\Boot\Bootloader\Bootloader; |
9
|
|
|
use Spiral\Bootloader\Http\Exception\ContextualObjectNotFoundException; |
10
|
|
|
use Spiral\Bootloader\Http\Exception\InvalidRequestScopeException; |
11
|
|
|
use Spiral\Config\ConfiguratorInterface; |
12
|
|
|
use Spiral\Config\Patch\Append; |
13
|
|
|
use Spiral\Cookies\Config\CookiesConfig; |
14
|
|
|
use Spiral\Cookies\CookieQueue; |
15
|
|
|
use Spiral\Core\Attribute\Singleton; |
16
|
|
|
use Spiral\Core\BinderInterface; |
17
|
|
|
use Spiral\Framework\Spiral; |
18
|
|
|
|
19
|
|
|
#[Singleton] |
20
|
|
|
final class CookiesBootloader extends Bootloader |
21
|
|
|
{ |
22
|
355 |
|
public function __construct( |
23
|
|
|
private readonly ConfiguratorInterface $config, |
24
|
|
|
private readonly BinderInterface $binder, |
25
|
|
|
) { |
26
|
355 |
|
} |
27
|
|
|
|
28
|
355 |
|
public function defineBindings(): array |
29
|
|
|
{ |
30
|
355 |
|
$this->binder->getBinder(Spiral::Http)->bind(CookieQueue::class, [self::class, 'cookieQueue']); |
|
|
|
|
31
|
|
|
|
32
|
355 |
|
return []; |
33
|
|
|
} |
34
|
|
|
|
35
|
355 |
|
public function init(): void |
36
|
|
|
{ |
37
|
355 |
|
$this->config->setDefaults( |
38
|
355 |
|
CookiesConfig::CONFIG, |
39
|
355 |
|
[ |
40
|
355 |
|
'domain' => '.%s', |
41
|
355 |
|
'method' => CookiesConfig::COOKIE_ENCRYPT, |
42
|
355 |
|
'excluded' => ['PHPSESSID', 'csrf-token'], |
43
|
355 |
|
] |
44
|
355 |
|
); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Disable protection for given cookie. |
49
|
|
|
*/ |
50
|
355 |
|
public function whitelistCookie(string $cookie): void |
51
|
|
|
{ |
52
|
355 |
|
$this->config->modify(CookiesConfig::CONFIG, new Append('excluded', null, $cookie)); |
53
|
|
|
} |
54
|
|
|
|
55
|
7 |
|
private function cookieQueue(?ServerRequestInterface $request): CookieQueue |
56
|
|
|
{ |
57
|
7 |
|
if ($request === null) { |
58
|
1 |
|
throw new InvalidRequestScopeException(CookieQueue::class); |
59
|
|
|
} |
60
|
|
|
|
61
|
6 |
|
return $request->getAttribute(CookieQueue::ATTRIBUTE) ?? throw new ContextualObjectNotFoundException( |
62
|
6 |
|
CookieQueue::class, |
63
|
6 |
|
CookieQueue::ATTRIBUTE, |
64
|
6 |
|
); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|