| 1: | <?php |
| 2: | |
| 3: | declare(strict_types=1); |
| 4: | |
| 5: | |
| 6: | |
| 7: | |
| 8: | |
| 9: | |
| 10: | |
| 11: | |
| 12: | |
| 13: | |
| 14: | namespace Nexus\Mcp\Core\Auth; |
| 15: | |
| 16: | use Nexus\Assert\Assert; |
| 17: | |
| 18: | |
| 19: | |
| 20: | |
| 21: | |
| 22: | |
| 23: | final readonly class ScopeSet |
| 24: | { |
| 25: | |
| 26: | |
| 27: | |
| 28: | |
| 29: | |
| 30: | public const string OFFLINE_ACCESS = 'offline_access'; |
| 31: | |
| 32: | |
| 33: | |
| 34: | |
| 35: | private const string SCOPE_TOKEN_PATTERN = '/\A[\x21\x23-\x5B\x5D-\x7E]+\z/'; |
| 36: | |
| 37: | |
| 38: | |
| 39: | |
| 40: | public array $values; |
| 41: | |
| 42: | |
| 43: | |
| 44: | |
| 45: | public function __construct(array $values = []) |
| 46: | { |
| 47: | Assert::that($values)->values()->isNonEmptyString('Each scope must be a non-empty string, {type} given.'); |
| 48: | |
| 49: | $this->values = array_values(array_unique($values)); |
| 50: | } |
| 51: | |
| 52: | |
| 53: | |
| 54: | |
| 55: | |
| 56: | |
| 57: | |
| 58: | public static function parse(?string $scope): self |
| 59: | { |
| 60: | return null === $scope ? new self() : self::fromList(explode(' ', $scope)); |
| 61: | } |
| 62: | |
| 63: | |
| 64: | |
| 65: | |
| 66: | |
| 67: | |
| 68: | public static function fromList(array $values): self |
| 69: | { |
| 70: | $kept = []; |
| 71: | |
| 72: | foreach ($values as $value) { |
| 73: | if (preg_match(self::SCOPE_TOKEN_PATTERN, $value) === 1) { |
| 74: | $kept[] = $value; |
| 75: | } |
| 76: | } |
| 77: | |
| 78: | return new self($kept); |
| 79: | } |
| 80: | |
| 81: | |
| 82: | |
| 83: | |
| 84: | public function mergeWith(self $other): self |
| 85: | { |
| 86: | return new self([...$this->values, ...$other->values]); |
| 87: | } |
| 88: | |
| 89: | public function contains(string $scope): bool |
| 90: | { |
| 91: | return \in_array($scope, $this->values, true); |
| 92: | } |
| 93: | |
| 94: | |
| 95: | |
| 96: | |
| 97: | public function without(string $scope): self |
| 98: | { |
| 99: | return new self(array_values(array_filter($this->values, static fn(string $value): bool => $value !== $scope))); |
| 100: | } |
| 101: | |
| 102: | public function containsAll(self $other): bool |
| 103: | { |
| 104: | foreach ($other->values as $value) { |
| 105: | if (! $this->contains($value)) { |
| 106: | return false; |
| 107: | } |
| 108: | } |
| 109: | |
| 110: | return true; |
| 111: | } |
| 112: | |
| 113: | |
| 114: | |
| 115: | |
| 116: | public function toParameter(): ?string |
| 117: | { |
| 118: | return [] === $this->values ? null : implode(' ', $this->values); |
| 119: | } |
| 120: | } |
| 121: | |