|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace WayOfDev\App\Entities; |
| 6 | + |
| 7 | +use Cycle\Database\DatabaseInterface; |
| 8 | +use JsonException; |
| 9 | +use JsonSerializable; |
| 10 | +use Ramsey\Uuid\Uuid; |
| 11 | +use Stringable; |
| 12 | + |
| 13 | +use function json_decode; |
| 14 | +use function json_encode; |
| 15 | + |
| 16 | +final class Footprint implements JsonSerializable, Stringable |
| 17 | +{ |
| 18 | + private UserId $id; |
| 19 | + |
| 20 | + private string $party; |
| 21 | + |
| 22 | + private string $realm; |
| 23 | + |
| 24 | + public static function empty(string $authorizedParty = 'guest-party', string $realm = 'guest-realm'): self |
| 25 | + { |
| 26 | + return new self(UserId::create(Uuid::NIL), $authorizedParty, $realm); |
| 27 | + } |
| 28 | + |
| 29 | + public static function random(string $authorizedParty = 'random-party', string $realm = 'random-realm'): self |
| 30 | + { |
| 31 | + return new self(UserId::create(Uuid::uuid7()->toString()), $authorizedParty, $realm); |
| 32 | + } |
| 33 | + |
| 34 | + public static function fromArray(array $data): self |
| 35 | + { |
| 36 | + $userId = UserId::fromString($data['id']); |
| 37 | + |
| 38 | + return new self($userId, $data['party'], $data['realm']); |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * https://cycle-orm.dev/docs/advanced-column-wrappers/2.x/en. |
| 43 | + * |
| 44 | + * @throws JsonException |
| 45 | + */ |
| 46 | + public static function castValue(string $value, DatabaseInterface $db): self |
| 47 | + { |
| 48 | + return self::fromArray( |
| 49 | + json_decode($value, true, 512, JSON_THROW_ON_ERROR) |
| 50 | + ); |
| 51 | + } |
| 52 | + |
| 53 | + public function toArray(): array |
| 54 | + { |
| 55 | + return [ |
| 56 | + 'id' => $this->id->toString(), |
| 57 | + 'party' => $this->party, |
| 58 | + 'realm' => $this->realm, |
| 59 | + ]; |
| 60 | + } |
| 61 | + |
| 62 | + public function id(): UserId |
| 63 | + { |
| 64 | + return $this->id; |
| 65 | + } |
| 66 | + |
| 67 | + public function party(): string |
| 68 | + { |
| 69 | + return $this->party; |
| 70 | + } |
| 71 | + |
| 72 | + public function realm(): string |
| 73 | + { |
| 74 | + return $this->realm; |
| 75 | + } |
| 76 | + |
| 77 | + public function jsonSerialize(): array |
| 78 | + { |
| 79 | + return $this->toArray(); |
| 80 | + } |
| 81 | + |
| 82 | + /** |
| 83 | + * @throws JsonException |
| 84 | + */ |
| 85 | + public function __toString(): string |
| 86 | + { |
| 87 | + return json_encode($this->toArray(), JSON_THROW_ON_ERROR); |
| 88 | + } |
| 89 | + |
| 90 | + private function __construct(UserId $id, string $party, string $realm) |
| 91 | + { |
| 92 | + $this->id = $id; |
| 93 | + $this->party = $party; |
| 94 | + $this->realm = $realm; |
| 95 | + } |
| 96 | +} |
0 commit comments