|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +namespace Salient\Http\OAuth2; |
| 4 | + |
| 5 | +use Salient\Contract\Core\Entity\Readable; |
| 6 | +use Salient\Contract\Core\Immutable; |
| 7 | +use Salient\Contract\Http\CredentialInterface; |
| 8 | +use Salient\Core\Concern\ReadableProtectedPropertiesTrait; |
| 9 | +use Salient\Utility\Date; |
| 10 | +use DateTimeImmutable; |
| 11 | +use DateTimeInterface; |
| 12 | +use InvalidArgumentException; |
| 13 | + |
| 14 | +/** |
| 15 | + * A token issued by an authorization provider for access to protected resources |
| 16 | + * |
| 17 | + * @property-read string $Token |
| 18 | + * @property-read string $Type |
| 19 | + * @property-read DateTimeImmutable|null $Expires |
| 20 | + * @property-read string[] $Scopes |
| 21 | + * @property-read array<string,mixed> $Claims |
| 22 | + */ |
| 23 | +final class AccessToken implements CredentialInterface, Immutable, Readable |
| 24 | +{ |
| 25 | + use ReadableProtectedPropertiesTrait; |
| 26 | + |
| 27 | + protected string $Token; |
| 28 | + protected string $Type; |
| 29 | + protected ?DateTimeImmutable $Expires; |
| 30 | + /** @var string[] */ |
| 31 | + protected array $Scopes; |
| 32 | + /** @var array<string,mixed> */ |
| 33 | + protected array $Claims; |
| 34 | + |
| 35 | + /** |
| 36 | + * @param DateTimeInterface|int|null $expires `null` if the access token's |
| 37 | + * lifetime is unknown, otherwise a {@see DateTimeInterface} or Unix |
| 38 | + * timestamp representing its expiration time. |
| 39 | + * @param string[]|null $scopes |
| 40 | + * @param array<string,mixed>|null $claims |
| 41 | + */ |
| 42 | + public function __construct( |
| 43 | + string $token, |
| 44 | + string $type, |
| 45 | + $expires, |
| 46 | + ?array $scopes = null, |
| 47 | + ?array $claims = null |
| 48 | + ) { |
| 49 | + if (is_int($expires) && $expires < 0) { |
| 50 | + throw new InvalidArgumentException(sprintf( |
| 51 | + 'Invalid $expires: %d', |
| 52 | + $expires |
| 53 | + )); |
| 54 | + } |
| 55 | + |
| 56 | + $this->Token = $token; |
| 57 | + $this->Type = $type; |
| 58 | + $this->Expires = $expires instanceof DateTimeInterface |
| 59 | + ? Date::immutable($expires) |
| 60 | + : ($expires === null |
| 61 | + ? null |
| 62 | + : new DateTimeImmutable("@$expires")); |
| 63 | + $this->Scopes = $scopes ?: []; |
| 64 | + $this->Claims = $claims ?: []; |
| 65 | + } |
| 66 | + |
| 67 | + /** |
| 68 | + * @inheritDoc |
| 69 | + */ |
| 70 | + public function getAuthenticationScheme(): string |
| 71 | + { |
| 72 | + return $this->Type; |
| 73 | + } |
| 74 | + |
| 75 | + /** |
| 76 | + * @inheritDoc |
| 77 | + */ |
| 78 | + public function getCredential(): string |
| 79 | + { |
| 80 | + return $this->Token; |
| 81 | + } |
| 82 | +} |
0 commit comments