Parse and validate AT Protocol Lexicons with DTO generation for Laravel
at dev 1.7 kB view raw
1<?php 2 3namespace SocialDept\AtpSchema\Data\Types; 4 5use SocialDept\AtpSchema\Data\TypeDefinition; 6use SocialDept\AtpSchema\Exceptions\RecordValidationException; 7 8class BooleanType extends TypeDefinition 9{ 10 /** 11 * Constant value. 12 */ 13 public readonly ?bool $const; 14 15 /** 16 * Create a new BooleanType. 17 */ 18 public function __construct( 19 ?string $description = null, 20 ?bool $const = null 21 ) { 22 parent::__construct('boolean', $description); 23 24 $this->const = $const; 25 } 26 27 /** 28 * Create from array data. 29 */ 30 public static function fromArray(array $data): self 31 { 32 return new self( 33 description: $data['description'] ?? null, 34 const: $data['const'] ?? null 35 ); 36 } 37 38 /** 39 * Convert to array. 40 */ 41 public function toArray(): array 42 { 43 $array = ['type' => $this->type]; 44 45 if ($this->description !== null) { 46 $array['description'] = $this->description; 47 } 48 49 if ($this->const !== null) { 50 $array['const'] = $this->const; 51 } 52 53 return $array; 54 } 55 56 /** 57 * Validate a value against this type definition. 58 */ 59 public function validate(mixed $value, string $path = ''): void 60 { 61 if (! is_bool($value)) { 62 throw RecordValidationException::invalidType($path, 'boolean', gettype($value)); 63 } 64 65 // Const validation 66 if ($this->const !== null && $value !== $this->const) { 67 $expected = $this->const ? 'true' : 'false'; 68 69 throw RecordValidationException::invalidValue($path, "must equal {$expected}"); 70 } 71 } 72}