1: <?php
2:
3: declare(strict_types=1);
4:
5: /**
6: * This file is part of the Nexus MCP SDK package.
7: *
8: * (c) 2026 John Paul E. Balandan, CPA <paulbalandan@gmail.com>
9: *
10: * For the full copyright and license information, please view
11: * the LICENSE file that was distributed with this source code.
12: */
13:
14: namespace Nexus\Mcp\Core\Schema\Resource;
15:
16: use Nexus\Assert\Assert;
17: use Nexus\Mcp\Core\Schema\Arrayable;
18: use Nexus\Mcp\Core\Schema\MetaObject;
19: use Nexus\Mcp\Core\Validation\Rfc3986UriValidator;
20:
21: /**
22: * The contents of a specific resource or sub-resource.
23: *
24: * @implements Arrayable<array{
25: * uri: non-empty-string,
26: * mimeType?: non-empty-string,
27: * _meta?: template-type<MetaObject, Arrayable, 'T'>,
28: * ...<string, mixed>
29: * }>
30: *
31: * @see https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/schema/2025-11-25/schema.ts
32: */
33: abstract readonly class ResourceContents implements Arrayable
34: {
35: /**
36: * @var non-empty-string
37: */
38: public string $uri;
39:
40: /**
41: * @var null|non-empty-string
42: */
43: public ?string $mimeType;
44:
45: public function __construct(
46: string $uri,
47: ?string $mimeType = null,
48: public MetaObject $meta = new MetaObject(),
49: ) {
50: Rfc3986UriValidator::validate($uri, 'resource contents "uri"');
51: Assert::that($mimeType)->nullOr()->isNonEmptyString('resource contents "mimeType" must be a non-empty string or null.');
52:
53: $this->uri = $uri;
54: $this->mimeType = $mimeType;
55: }
56:
57: /**
58: * @param array<string, mixed> $data
59: */
60: #[\Override]
61: abstract public static function fromArray(array $data): static;
62:
63: /**
64: * Serializes the shared fields. Subclasses override to merge their own
65: * payload field alongside the slice returned here.
66: */
67: #[\Override]
68: public function toArray(): array
69: {
70: $data = ['uri' => $this->uri];
71:
72: if (null !== $this->mimeType) {
73: $data['mimeType'] = $this->mimeType;
74: }
75:
76: $meta = $this->meta->toArray();
77:
78: if ([] !== $meta) {
79: $data['_meta'] = $meta;
80: }
81:
82: return $data;
83: }
84:
85: #[\Override]
86: public function jsonSerialize(): array
87: {
88: return $this->toArray();
89: }
90: }
91: