Parse and validate AT Protocol Lexicons with DTO generation for Laravel
1<?php
2
3namespace SocialDept\AtpSchema\Data\Types;
4
5use SocialDept\AtpSchema\Data\TypeDefinition;
6use SocialDept\AtpSchema\Exceptions\RecordValidationException;
7
8class CidLinkType extends TypeDefinition
9{
10 /**
11 * Create a new CidLinkType.
12 */
13 public function __construct(?string $description = null)
14 {
15 parent::__construct('cid-link', $description);
16 }
17
18 /**
19 * Create from array data.
20 */
21 public static function fromArray(array $data): self
22 {
23 return new self(
24 description: $data['description'] ?? null
25 );
26 }
27
28 /**
29 * Convert to array.
30 */
31 public function toArray(): array
32 {
33 $array = ['type' => $this->type];
34
35 if ($this->description !== null) {
36 $array['description'] = $this->description;
37 }
38
39 return $array;
40 }
41
42 /**
43 * Validate a value against this type definition.
44 */
45 public function validate(mixed $value, string $path = ''): void
46 {
47 if (! is_array($value)) {
48 throw RecordValidationException::invalidType($path, 'cid-link (object with $link)', gettype($value));
49 }
50
51 if (! isset($value['$link'])) {
52 throw RecordValidationException::invalidValue($path, 'must contain $link property');
53 }
54
55 $link = $value['$link'];
56
57 if (! is_string($link)) {
58 throw RecordValidationException::invalidValue($path, '$link must be a string');
59 }
60
61 // Basic CID validation
62 if (! preg_match('/^[a-zA-Z0-9]+$/', $link)) {
63 throw RecordValidationException::invalidValue($path, '$link must be a valid CID');
64 }
65 }
66}