Skip to content

Commit af67ed4

Browse files
committed
feat(date): validate format template strings
1 parent e7a7ab2 commit af67ed4

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed

src/Elements/RichTexts/Date.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
use SlackPhp\BlockKit\Property;
88
use SlackPhp\BlockKit\Validation\RequiresAllOf;
9+
use SlackPhp\BlockKit\Validation\ValidDateFormat;
910
use SlackPhp\BlockKit\Validation\ValidString;
1011
use SlackPhp\BlockKit\Validation\ValidUrl;
1112

@@ -18,7 +19,7 @@ class Date extends RichTextElement
1819
#[Property]
1920
public ?int $timestamp;
2021

21-
#[Property, ValidString]
22+
#[Property, ValidDateFormat]
2223
public ?string $format;
2324

2425
#[Property, ValidUrl]

src/Validation/ValidDateFormat.php

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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

Comments
 (0)