Skip to content

Commit f53dcb3

Browse files
committed
User: identity and authenticated state are cached, UserStorage is not called repeatedly
1 parent db73664 commit f53dcb3

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

src/Security/User.php

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,12 @@ class User
5353
/** @var IAuthorizator|null */
5454
private $authorizator;
5555

56+
/** @var IIdentity|null|false false means undefined */
57+
private $identity = false;
58+
59+
/** @var bool|null */
60+
private $authenticated;
61+
5662

5763
public function __construct(IUserStorage $storage, IAuthenticator $authenticator = null, IAuthorizator $authorizator = null)
5864
{
@@ -84,6 +90,8 @@ public function login($user, string $password = null): void
8490
}
8591
$this->storage->setIdentity($user);
8692
$this->storage->setAuthenticated(true);
93+
$this->identity = $user;
94+
$this->authenticated = true;
8795
$this->onLoggedIn($this);
8896
}
8997

@@ -96,9 +104,11 @@ final public function logout(bool $clearIdentity = false): void
96104
if ($this->isLoggedIn()) {
97105
$this->onLoggedOut($this);
98106
$this->storage->setAuthenticated(false);
107+
$this->authenticated = false;
99108
}
100109
if ($clearIdentity) {
101110
$this->storage->setIdentity(null);
111+
$this->identity = null;
102112
}
103113
}
104114

@@ -108,7 +118,10 @@ final public function logout(bool $clearIdentity = false): void
108118
*/
109119
final public function isLoggedIn(): bool
110120
{
111-
return $this->storage->isAuthenticated();
121+
if ($this->authenticated === null) {
122+
$this->authenticated = $this->storage->isAuthenticated();
123+
}
124+
return $this->authenticated;
112125
}
113126

114127

@@ -117,7 +130,10 @@ final public function isLoggedIn(): bool
117130
*/
118131
final public function getIdentity(): ?IIdentity
119132
{
120-
return $this->storage->getIdentity();
133+
if ($this->identity === false) {
134+
$this->identity = $this->storage->getIdentity();
135+
}
136+
return $this->identity;
121137
}
122138

123139

0 commit comments

Comments
 (0)