|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace SlackPhp\BlockKit\Validation; |
| 6 | + |
| 7 | +use Attribute; |
| 8 | +use SlackPhp\BlockKit\Component; |
| 9 | + |
| 10 | +#[Attribute(Attribute::TARGET_PROPERTY)] |
| 11 | +class ValidDateFormat implements PropertyRule |
| 12 | +{ |
| 13 | + private const ALLOWED_TEMPLATES = [ |
| 14 | + 'ago', |
| 15 | + 'date', |
| 16 | + 'date_long', |
| 17 | + 'date_long_full', |
| 18 | + 'date_long_pretty', |
| 19 | + 'date_num', |
| 20 | + 'date_pretty', |
| 21 | + 'date_short', |
| 22 | + 'date_short_pretty', |
| 23 | + 'date_slash', |
| 24 | + 'day_divider_pretty', |
| 25 | + 'time', |
| 26 | + 'time_secs', |
| 27 | + ]; |
| 28 | + |
| 29 | + public function check(Component $component, string $field, mixed $value): void |
| 30 | + { |
| 31 | + if ($value === null) { |
| 32 | + return; |
| 33 | + } |
| 34 | + |
| 35 | + $format = (string) $value; |
| 36 | + |
| 37 | + $templates = implode(', ', self::ALLOWED_TEMPLATES); |
| 38 | + $templateRegex = implode('|', self::ALLOWED_TEMPLATES); |
| 39 | + $validTemplatesRegex = '/^(?:(?!{[^{}]*}).|{(?:' . $templateRegex . ')})*$/'; |
| 40 | + $containsTemplateRegex = '/{(?:' . $templateRegex . ')}/'; |
| 41 | + |
| 42 | + if (preg_match($validTemplatesRegex, $format) !== 1) { |
| 43 | + throw new ValidationException( |
| 44 | + 'The "%s" field of a valid "%s" component can only contain valid template strings (%s)', |
| 45 | + [$field, $component->type->value, $templates], |
| 46 | + ); |
| 47 | + } |
| 48 | + |
| 49 | + if (preg_match($containsTemplateRegex, $format) !== 1) { |
| 50 | + throw new ValidationException( |
| 51 | + 'The "%s" field of a valid "%s" component must at least contain one valid template string (%s)', |
| 52 | + [$field, $component->type->value, $templates], |
| 53 | + ); |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments