Skip to content

Commit 517fb7e

Browse files
committed
feat(validation): add HexColor validation rule
1 parent ea417ae commit 517fb7e

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
}
18+
19+
public function isValid(mixed $value): bool
20+
{
21+
if ($this->orNull && $value === null) {
22+
return true;
23+
}
24+
25+
if (! is_string($value)) {
26+
return false;
27+
}
28+
29+
return preg_match('/^#(?:(?:[0-9a-f]{3}){1,2}|(?:[0-9a-f]{4}){1,2})$/i', $value) === 1;
30+
}
31+
32+
public function message(): string
33+
{
34+
return 'Value should be a valid hexadecimal color.';
35+
}
36+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
26+
$this->assertTrue($rule->isValid('#ffffff'));
27+
$this->assertTrue($rule->isValid('#FFFFFF'));
28+
$this->assertTrue($rule->isValid('#fff'));
29+
}
30+
}

0 commit comments

Comments
 (0)