| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace WP\McpSchema\Common\Protocol\Factory; |
| 6 |
|
| 7 |
use WP\McpSchema\Common\Protocol\Union\ContentBlockInterface; |
| 8 |
use WP\McpSchema\Common\Content\DTO\TextContent; |
| 9 |
use WP\McpSchema\Common\Content\DTO\ImageContent; |
| 10 |
use WP\McpSchema\Common\Content\DTO\AudioContent; |
| 11 |
use WP\McpSchema\Server\Resources\DTO\ResourceLink; |
| 12 |
use WP\McpSchema\Common\Protocol\DTO\EmbeddedResource; |
| 13 |
|
| 14 |
/** |
| 15 |
* Factory for creating ContentBlock union type instances. |
| 16 |
* |
| 17 |
* @mcp-domain Common |
| 18 |
* @mcp-subdomain Protocol |
| 19 |
* @mcp-version 2025-11-25 |
| 20 |
*/ |
| 21 |
final class ContentBlockFactory |
| 22 |
{ |
| 23 |
/** |
| 24 |
* Registry mapping discriminator values to implementation classes. |
| 25 |
* |
| 26 |
* @var array<string, class-string<ContentBlockInterface>> |
| 27 |
*/ |
| 28 |
public const REGISTRY = [ |
| 29 |
'text' => TextContent::class, |
| 30 |
'image' => ImageContent::class, |
| 31 |
'audio' => AudioContent::class, |
| 32 |
'resource_link' => ResourceLink::class, |
| 33 |
'resource' => EmbeddedResource::class, |
| 34 |
]; |
| 35 |
|
| 36 |
/** |
| 37 |
* Creates an instance from an array. |
| 38 |
* |
| 39 |
* @param array<string, mixed> $data |
| 40 |
* @return ContentBlockInterface |
| 41 |
* @throws \InvalidArgumentException |
| 42 |
*/ |
| 43 |
public static function fromArray(array $data): ContentBlockInterface |
| 44 |
{ |
| 45 |
if (!isset($data['type'])) { |
| 46 |
throw new \InvalidArgumentException('Missing discriminator field: type'); |
| 47 |
} |
| 48 |
|
| 49 |
/** @var string $type */ |
| 50 |
$type = $data['type']; |
| 51 |
if (!isset(self::REGISTRY[$type])) { |
| 52 |
throw new \InvalidArgumentException(sprintf( |
| 53 |
"Unknown type value '%s'. Valid values: %s", |
| 54 |
$type, |
| 55 |
implode(', ', array_keys(self::REGISTRY)) |
| 56 |
)); |
| 57 |
} |
| 58 |
|
| 59 |
$class = self::REGISTRY[$type]; |
| 60 |
return $class::fromArray($data); |
| 61 |
} |
| 62 |
|
| 63 |
/** |
| 64 |
* Checks if a type value is supported by this factory. |
| 65 |
* |
| 66 |
* @param string $type |
| 67 |
* @return bool |
| 68 |
*/ |
| 69 |
public static function supports(string $type): bool |
| 70 |
{ |
| 71 |
return isset(self::REGISTRY[$type]); |
| 72 |
} |
| 73 |
|
| 74 |
/** |
| 75 |
* Returns all supported type values. |
| 76 |
* |
| 77 |
* @return array<string> |
| 78 |
*/ |
| 79 |
public static function types(): array |
| 80 |
{ |
| 81 |
return array_keys(self::REGISTRY); |
| 82 |
} |
| 83 |
} |
| 84 |
|