Parse and validate AT Protocol Lexicons with DTO generation for Laravel
1<?php
2
3namespace SocialDept\AtpSchema\Data;
4
5abstract class TypeDefinition
6{
7 /**
8 * Type identifier (string, number, object, array, etc).
9 */
10 public readonly string $type;
11
12 /**
13 * Optional description of this type.
14 */
15 public readonly ?string $description;
16
17 /**
18 * Create a new TypeDefinition.
19 */
20 public function __construct(
21 string $type,
22 ?string $description = null
23 ) {
24 $this->type = $type;
25 $this->description = $description;
26 }
27
28 /**
29 * Create type definition from array data.
30 */
31 abstract public static function fromArray(array $data): self;
32
33 /**
34 * Convert type definition to array.
35 */
36 abstract public function toArray(): array;
37
38 /**
39 * Validate a value against this type definition.
40 *
41 * @throws \SocialDept\AtpSchema\Exceptions\RecordValidationException
42 */
43 abstract public function validate(mixed $value, string $path = ''): void;
44
45 /**
46 * Check if this is a primitive type.
47 */
48 public function isPrimitive(): bool
49 {
50 return in_array($this->type, [
51 'null',
52 'boolean',
53 'integer',
54 'string',
55 'bytes',
56 'cid-link',
57 'unknown',
58 ]);
59 }
60
61 /**
62 * Check if this is an object type.
63 */
64 public function isObject(): bool
65 {
66 return $this->type === 'object';
67 }
68
69 /**
70 * Check if this is an array type.
71 */
72 public function isArray(): bool
73 {
74 return $this->type === 'array';
75 }
76
77 /**
78 * Check if this is a union type.
79 */
80 public function isUnion(): bool
81 {
82 return $this->type === 'union';
83 }
84
85 /**
86 * Check if this is a ref type.
87 */
88 public function isRef(): bool
89 {
90 return $this->type === 'ref';
91 }
92
93 /**
94 * Check if this is a blob type.
95 */
96 public function isBlob(): bool
97 {
98 return $this->type === 'blob';
99 }
100
101 /**
102 * Get the type identifier.
103 */
104 public function getType(): string
105 {
106 return $this->type;
107 }
108
109 /**
110 * Get the description.
111 */
112 public function getDescription(): ?string
113 {
114 return $this->description;
115 }
116}