Parse and validate AT Protocol Lexicons with DTO generation for Laravel
at dev 2.0 kB view raw
1<?php 2 3namespace SocialDept\AtpSchema\Parser; 4 5use SocialDept\AtpSchema\Data\TypeDefinition; 6use SocialDept\AtpSchema\Data\Types\BooleanType; 7use SocialDept\AtpSchema\Data\Types\BytesType; 8use SocialDept\AtpSchema\Data\Types\CidLinkType; 9use SocialDept\AtpSchema\Data\Types\IntegerType; 10use SocialDept\AtpSchema\Data\Types\NullType; 11use SocialDept\AtpSchema\Data\Types\StringType; 12use SocialDept\AtpSchema\Data\Types\UnknownType; 13use SocialDept\AtpSchema\Exceptions\TypeResolutionException; 14 15class PrimitiveParser 16{ 17 /** 18 * Parse a primitive type definition from array data. 19 * 20 * @throws TypeResolutionException 21 */ 22 public function parse(array $data): TypeDefinition 23 { 24 $type = $data['type'] ?? null; 25 26 if ($type === null) { 27 throw TypeResolutionException::unknownType('(missing type field)'); 28 } 29 30 return match ($type) { 31 'null' => NullType::fromArray($data), 32 'boolean' => BooleanType::fromArray($data), 33 'integer' => IntegerType::fromArray($data), 34 'string' => StringType::fromArray($data), 35 'bytes' => BytesType::fromArray($data), 36 'cid-link' => CidLinkType::fromArray($data), 37 'unknown' => UnknownType::fromArray($data), 38 default => throw TypeResolutionException::unknownType($type), 39 }; 40 } 41 42 /** 43 * Check if a type is a primitive type. 44 */ 45 public function isPrimitive(string $type): bool 46 { 47 return in_array($type, [ 48 'null', 49 'boolean', 50 'integer', 51 'string', 52 'bytes', 53 'cid-link', 54 'unknown', 55 ]); 56 } 57 58 /** 59 * Get all supported primitive types. 60 * 61 * @return array<string> 62 */ 63 public function getSupportedTypes(): array 64 { 65 return [ 66 'null', 67 'boolean', 68 'integer', 69 'string', 70 'bytes', 71 'cid-link', 72 'unknown', 73 ]; 74 } 75}