File tree Expand file tree Collapse file tree 2 files changed +67
-0
lines changed
Expand file tree Collapse file tree 2 files changed +67
-0
lines changed Original file line number Diff line number Diff line change 1+ <?php
2+
3+ declare (strict_types=1 );
4+
5+ namespace Tempest \Validation \Rules ;
6+
7+ use Attribute ;
8+ use Tempest \Validation \Rule ;
9+
10+ #[Attribute]
11+ final readonly class HexColor implements Rule
12+ {
13+ public function __construct (
14+ private bool $ orNull = false ,
15+ ) {}
16+
17+ public function isValid (mixed $ value ): bool
18+ {
19+ if ($ this ->orNull && $ value === null ) {
20+ return true ;
21+ }
22+
23+ if (! is_string ($ value )) {
24+ return false ;
25+ }
26+
27+ return preg_match ('/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{4}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/i ' , $ value ) === 1 ;
28+ }
29+
30+ public function message (): string
31+ {
32+ return 'Value should be a valid hexadecimal color. ' ;
33+ }
34+ }
Original file line number Diff line number Diff line change 1+ <?php
2+
3+ declare (strict_types=1 );
4+
5+ namespace Tempest \Validation \Tests \Rules ;
6+
7+ use PHPUnit \Framework \TestCase ;
8+ use Tempest \Validation \Rules \HexColor ;
9+
10+ /**
11+ * @internal
12+ */
13+ final class HexColorTest extends TestCase
14+ {
15+ public function test_uuid (): void
16+ {
17+ $ rule = new HexColor ();
18+
19+ $ this ->assertSame ('Value should be a valid hexadecimal color. ' , $ rule ->message ());
20+
21+ $ this ->assertFalse ($ rule ->isValid ('string_123 ' ));
22+ $ this ->assertFalse ($ rule ->isValid ([])); // Should return false, not a TypeError from preg_match
23+ $ this ->assertFalse ($ rule ->isValid ('ffffff ' ));
24+ $ this ->assertFalse ($ rule ->isValid ('#fffffff ' ));
25+ $ this ->assertFalse ($ rule ->isValid ('#fffaa ' ));
26+
27+ $ this ->assertTrue ($ rule ->isValid ('#ffffff ' ));
28+ $ this ->assertTrue ($ rule ->isValid ('#FFFFFF ' ));
29+ $ this ->assertTrue ($ rule ->isValid ('#FFFFFFAA ' ));
30+ $ this ->assertTrue ($ rule ->isValid ('#fff ' ));
31+ $ this ->assertTrue ($ rule ->isValid ('#fffa ' ));
32+ }
33+ }
You can’t perform that action at this time.
0 commit comments