| 1: | <?php |
| 2: | |
| 3: | declare(strict_types=1); |
| 4: | |
| 5: | |
| 6: | |
| 7: | |
| 8: | |
| 9: | |
| 10: | |
| 11: | |
| 12: | |
| 13: | |
| 14: | namespace Nexus\Mcp\Core\Schema\Result; |
| 15: | |
| 16: | use Nexus\Assert\Assert; |
| 17: | use Nexus\Mcp\Core\Schema\Cursor; |
| 18: | use Nexus\Mcp\Core\Schema\MetaObject; |
| 19: | use Nexus\Mcp\Core\Schema\Resource\Resource; |
| 20: | |
| 21: | |
| 22: | |
| 23: | |
| 24: | |
| 25: | |
| 26: | final readonly class ListResourcesResult extends PaginatedResult implements ServerResult |
| 27: | { |
| 28: | |
| 29: | |
| 30: | |
| 31: | public array $resources; |
| 32: | |
| 33: | |
| 34: | |
| 35: | |
| 36: | public function __construct(array $resources, ?Cursor $nextCursor = null, MetaObject $meta = new MetaObject()) |
| 37: | { |
| 38: | Assert::that($resources) |
| 39: | ->isList('"result.resources" must be a list, non-list array given.') |
| 40: | ->values()->isInstanceOf(Resource::class) |
| 41: | ; |
| 42: | |
| 43: | $this->resources = $resources; |
| 44: | |
| 45: | parent::__construct($nextCursor, $meta); |
| 46: | } |
| 47: | |
| 48: | #[\Override] |
| 49: | public static function fromArray(array $data): static |
| 50: | { |
| 51: | Assert::that($data)->hasOffset('resources', '"result" missing the required "resources" key.'); |
| 52: | Assert::that($data['resources']) |
| 53: | ->isList('"result.resources" must be a list, {type} given.') |
| 54: | ->values() |
| 55: | ->isArray('each "result.resource" must be an object, {type} given.') |
| 56: | ->isMap('each "result.resource" must be a string-keyed object.') |
| 57: | ; |
| 58: | $resources = array_map(Resource::fromArray(...), $data['resources']); |
| 59: | |
| 60: | $nextCursor = null; |
| 61: | |
| 62: | if (\array_key_exists('nextCursor', $data)) { |
| 63: | $raw = $data['nextCursor']; |
| 64: | Assert::that($raw)->isString('"result.nextCursor" must be a string, {type} given.'); |
| 65: | $nextCursor = new Cursor($raw); |
| 66: | } |
| 67: | |
| 68: | $meta = new MetaObject(); |
| 69: | |
| 70: | if (\array_key_exists('_meta', $data)) { |
| 71: | Assert::that($data['_meta']) |
| 72: | ->isArray('"result._meta" must be an object, {type} given.') |
| 73: | ->isMap('"result._meta" must be a string-keyed object.') |
| 74: | ; |
| 75: | $meta = MetaObject::fromArray($data['_meta']); |
| 76: | } |
| 77: | |
| 78: | return new self($resources, $nextCursor, $meta); |
| 79: | } |
| 80: | |
| 81: | #[\Override] |
| 82: | public function toArray(): array |
| 83: | { |
| 84: | return [ |
| 85: | ...parent::toArray(), |
| 86: | 'resources' => array_map(static fn(Resource $resource): array => $resource->toArray(), $this->resources), |
| 87: | ]; |
| 88: | } |
| 89: | |
| 90: | #[\Override] |
| 91: | public function jsonSerialize(): array |
| 92: | { |
| 93: | return $this->toArray(); |
| 94: | } |
| 95: | } |
| 96: | |