Parse and validate AT Protocol Lexicons with DTO generation for Laravel
1<?php
2
3namespace SocialDept\AtpSchema\Validation\Rules;
4
5use Closure;
6use DateTime;
7use Illuminate\Contracts\Validation\ValidationRule;
8
9class AtDatetime implements ValidationRule
10{
11 /**
12 * Run the validation rule.
13 */
14 public function validate(string $attribute, mixed $value, Closure $fail): void
15 {
16 if (! is_string($value)) {
17 $fail("The {$attribute} must be a string.");
18
19 return;
20 }
21
22 if (! $this->isValidAtDatetime($value)) {
23 $fail("The {$attribute} is not a valid AT Protocol datetime.");
24 }
25 }
26
27 /**
28 * Validate AT Protocol datetime format.
29 *
30 * Must be ISO 8601 format with timezone (typically UTC)
31 * Example: 2024-01-01T00:00:00Z or 2024-01-01T00:00:00.000Z
32 */
33 protected function isValidAtDatetime(string $value): bool
34 {
35 // Try to parse as DateTime with ISO 8601 format
36 $datetime = DateTime::createFromFormat(DateTime::ATOM, $value);
37
38 if ($datetime !== false) {
39 return true;
40 }
41
42 // Also try with milliseconds
43 $datetime = DateTime::createFromFormat('Y-m-d\TH:i:s.u\Z', $value);
44
45 if ($datetime !== false) {
46 return true;
47 }
48
49 // Try standard ISO 8601 with Z
50 $datetime = DateTime::createFromFormat('Y-m-d\TH:i:s\Z', $value);
51
52 return $datetime !== false;
53 }
54}