|
12 | 12 |
|
13 | 13 | /** |
14 | 14 | * Default implementation of IIdentity. |
| 15 | + * @property string|int $id |
| 16 | + * @property array $roles |
| 17 | + * @property array $data |
15 | 18 | */ |
16 | | -class SimpleIdentity extends Identity |
| 19 | +class SimpleIdentity implements IIdentity |
17 | 20 | { |
| 21 | + private string|int $id; |
| 22 | + private array $roles; |
| 23 | + |
| 24 | + /** @var mixed[] */ |
| 25 | + private array $data; |
| 26 | + |
| 27 | + |
| 28 | + public function __construct(string|int $id, $roles = null, ?iterable $data = null) |
| 29 | + { |
| 30 | + $this->setId($id); |
| 31 | + $this->setRoles((array) $roles); |
| 32 | + $this->data = iterator_to_array($data ?? []); |
| 33 | + } |
| 34 | + |
| 35 | + |
| 36 | + /** |
| 37 | + * Sets the ID of user. |
| 38 | + */ |
| 39 | + public function setId(string|int $id): static |
| 40 | + { |
| 41 | + $this->id = is_numeric($id) && !is_float($tmp = $id * 1) ? $tmp : $id; |
| 42 | + return $this; |
| 43 | + } |
| 44 | + |
| 45 | + |
| 46 | + /** |
| 47 | + * Returns the ID of user. |
| 48 | + */ |
| 49 | + public function getId(): string|int |
| 50 | + { |
| 51 | + return $this->id; |
| 52 | + } |
| 53 | + |
| 54 | + |
| 55 | + /** |
| 56 | + * Sets a list of roles that the user is a member of. |
| 57 | + */ |
| 58 | + public function setRoles(array $roles): static |
| 59 | + { |
| 60 | + $this->roles = $roles; |
| 61 | + return $this; |
| 62 | + } |
| 63 | + |
| 64 | + |
| 65 | + /** |
| 66 | + * Returns a list of roles that the user is a member of. |
| 67 | + */ |
| 68 | + public function getRoles(): array |
| 69 | + { |
| 70 | + return $this->roles; |
| 71 | + } |
| 72 | + |
| 73 | + |
| 74 | + /** |
| 75 | + * Returns a user data. |
| 76 | + * @return mixed[] |
| 77 | + */ |
| 78 | + public function getData(): array |
| 79 | + { |
| 80 | + return $this->data; |
| 81 | + } |
| 82 | + |
| 83 | + |
| 84 | + /** |
| 85 | + * Sets user data value. |
| 86 | + */ |
| 87 | + public function __set(string $key, mixed $value): void |
| 88 | + { |
| 89 | + if (in_array($key, ['id', 'roles', 'data'], strict: true)) { |
| 90 | + $this->{"set$key"}($value); |
| 91 | + |
| 92 | + } else { |
| 93 | + $this->data[$key] = $value; |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + |
| 98 | + /** |
| 99 | + * Returns user data value. |
| 100 | + */ |
| 101 | + public function &__get(string $key): mixed |
| 102 | + { |
| 103 | + if (in_array($key, ['id', 'roles', 'data'], strict: true)) { |
| 104 | + $res = $this->{"get$key"}(); |
| 105 | + return $res; |
| 106 | + |
| 107 | + } else { |
| 108 | + return $this->data[$key]; |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + |
| 113 | + public function __isset(string $key): bool |
| 114 | + { |
| 115 | + return isset($this->data[$key]) || in_array($key, ['id', 'roles', 'data'], strict: true); |
| 116 | + } |
18 | 117 | } |
0 commit comments