| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace WP\McpSchema\Client\Elicitation\Factory; |
| 6 |
|
| 7 |
use WP\McpSchema\Client\Elicitation\Union\EnumSchemaInterface; |
| 8 |
use WP\McpSchema\Client\Elicitation\Factory\SingleSelectEnumSchemaFactory; |
| 9 |
use WP\McpSchema\Client\Elicitation\Factory\MultiSelectEnumSchemaFactory; |
| 10 |
use WP\McpSchema\Client\Elicitation\DTO\LegacyTitledEnumSchema; |
| 11 |
|
| 12 |
/** |
| 13 |
* Factory for creating EnumSchema union type instances. |
| 14 |
* |
| 15 |
* @mcp-domain Client |
| 16 |
* @mcp-subdomain Elicitation |
| 17 |
* @mcp-version 2025-11-25 |
| 18 |
*/ |
| 19 |
final class EnumSchemaFactory |
| 20 |
{ |
| 21 |
/** |
| 22 |
* Registry mapping discriminator values to implementation classes. |
| 23 |
* Note: Some values route to other factories for nested union resolution. |
| 24 |
* |
| 25 |
* @var array<string, class-string> |
| 26 |
*/ |
| 27 |
public const REGISTRY = [ |
| 28 |
'array' => MultiSelectEnumSchemaFactory::class, |
| 29 |
'string' => LegacyTitledEnumSchema::class, |
| 30 |
]; |
| 31 |
|
| 32 |
/** |
| 33 |
* Creates an instance from an array. |
| 34 |
* |
| 35 |
* @param array<string, mixed> $data |
| 36 |
* @return EnumSchemaInterface |
| 37 |
* @throws \InvalidArgumentException |
| 38 |
*/ |
| 39 |
public static function fromArray(array $data): EnumSchemaInterface |
| 40 |
{ |
| 41 |
if (!isset($data['type'])) { |
| 42 |
throw new \InvalidArgumentException('Missing discriminator field: type'); |
| 43 |
} |
| 44 |
|
| 45 |
switch ($data['type']) { |
| 46 |
case 'array': |
| 47 |
return MultiSelectEnumSchemaFactory::fromArray($data); |
| 48 |
case 'string': |
| 49 |
if (isset($data['oneOf'])) { |
| 50 |
return SingleSelectEnumSchemaFactory::fromArray($data); |
| 51 |
} |
| 52 |
elseif (isset($data['enumNames'])) { |
| 53 |
return LegacyTitledEnumSchema::fromArray($data); |
| 54 |
} |
| 55 |
else { |
| 56 |
return LegacyTitledEnumSchema::fromArray($data); |
| 57 |
} |
| 58 |
default: |
| 59 |
throw new \InvalidArgumentException(sprintf( |
| 60 |
"Unknown type value '%s'. Valid values: %s", |
| 61 |
is_scalar($data['type']) ? $data['type'] : gettype($data['type']), |
| 62 |
implode(', ', array_keys(self::REGISTRY)) |
| 63 |
)); |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
/** |
| 68 |
* Checks if a type value is supported by this factory. |
| 69 |
* |
| 70 |
* @param string $type |
| 71 |
* @return bool |
| 72 |
*/ |
| 73 |
public static function supports(string $type): bool |
| 74 |
{ |
| 75 |
return isset(self::REGISTRY[$type]); |
| 76 |
} |
| 77 |
|
| 78 |
/** |
| 79 |
* Returns all supported type values. |
| 80 |
* |
| 81 |
* @return array<string> |
| 82 |
*/ |
| 83 |
public static function types(): array |
| 84 |
{ |
| 85 |
return array_keys(self::REGISTRY); |
| 86 |
} |
| 87 |
} |
| 88 |
|