1 | <?php |
||
23 | final class LazySession implements SessionInterface |
||
24 | { |
||
25 | /** @internal do not access directly: use {@see LazySession::getRealSession} instead */ |
||
26 | private ?SessionInterface $realSession = null; |
||
|
|||
27 | |||
28 | /** @var callable */ |
||
29 | private $sessionLoader; |
||
30 | |||
31 | /** |
||
32 | * Instantiation via __construct is not allowed, use {@see LazySession::fromContainerBuildingCallback} instead |
||
33 | */ |
||
34 | 57 | private function __construct() |
|
35 | { |
||
36 | 57 | } |
|
37 | |||
38 | 57 | public static function fromContainerBuildingCallback(callable $sessionLoader) : self |
|
39 | { |
||
40 | 57 | $instance = new self(); |
|
41 | |||
42 | 57 | $instance->sessionLoader = $sessionLoader; |
|
43 | |||
44 | 57 | return $instance; |
|
45 | } |
||
46 | |||
47 | /** |
||
48 | * {@inheritDoc} |
||
49 | */ |
||
50 | 21 | public function set(string $key, $value) : void |
|
51 | { |
||
52 | 21 | $this->getRealSession()->set($key, $value); |
|
53 | 21 | } |
|
54 | |||
55 | /** |
||
56 | * {@inheritDoc} |
||
57 | */ |
||
58 | 7 | public function get(string $key, $default = null) |
|
59 | { |
||
60 | 7 | return $this->getRealSession()->get($key, $default); |
|
61 | } |
||
62 | |||
63 | 2 | public function remove(string $key) : void |
|
64 | { |
||
65 | 2 | $this->getRealSession()->remove($key); |
|
66 | 2 | } |
|
67 | |||
68 | 4 | public function clear() : void |
|
69 | { |
||
70 | 4 | $this->getRealSession()->clear(); |
|
71 | 4 | } |
|
72 | |||
73 | 1 | public function has(string $key) : bool |
|
74 | { |
||
75 | 1 | return $this->getRealSession()->has($key); |
|
76 | } |
||
77 | |||
78 | 50 | public function hasChanged() : bool |
|
79 | { |
||
80 | 50 | return $this->realSession && $this->realSession->hasChanged(); |
|
81 | } |
||
82 | |||
83 | 44 | public function isEmpty() : bool |
|
84 | { |
||
85 | 44 | return $this->getRealSession()->isEmpty(); |
|
86 | } |
||
87 | |||
88 | 26 | public function jsonSerialize() : object |
|
89 | { |
||
90 | 26 | return $this->getRealSession()->jsonSerialize(); |
|
91 | } |
||
92 | |||
93 | /** |
||
94 | * Get or initialize the session |
||
95 | */ |
||
96 | 51 | private function getRealSession() : SessionInterface |
|
97 | { |
||
98 | 51 | return $this->realSession ?? $this->realSession = $this->loadSession(); |
|
99 | } |
||
100 | |||
101 | /** |
||
102 | * Type-safe wrapper that ensures that the given callback returns the expected type of object, when called |
||
103 | */ |
||
104 | 51 | private function loadSession() : SessionInterface |
|
105 | { |
||
106 | 51 | $sessionLoader = $this->sessionLoader; |
|
107 | |||
108 | 51 | return $sessionLoader(); |
|
109 | } |
||
110 | } |
||
111 |