Skip to content

Commit 61ccfcc

Browse files
committed
Add HEX color validation rule
1 parent b5e6c9a commit 61ccfcc

File tree

3 files changed

+74
-0
lines changed

3 files changed

+74
-0
lines changed

src/Rules/HexColorRule.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Wrkflow\GetValue\Rules;
6+
7+
use Wrkflow\GetValue\Contracts\RuleContract;
8+
9+
class HexColorRule implements RuleContract
10+
{
11+
public function passes(mixed $value): bool
12+
{
13+
if (is_string($value) === false) {
14+
return false;
15+
}
16+
17+
return (new RegexRule('/^#{0,1}[A-Fa-f0-9]{3,6}$/'))->passes($value);
18+
}
19+
}

src/Rules/RegexRule.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@ public function __construct(protected readonly string $pattern)
1717

1818
public function passes(mixed $value): bool
1919
{
20+
if (is_string($value) === false && is_numeric($value) === false) {
21+
return false;
22+
}
23+
2024
$result = preg_match($this->pattern, (string) $value);
2125

2226
return $result !== false && $result !== 0;

tests/Rules/HexColorRuleTest.php

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Wrkflow\GetValueTests\Rules;
6+
7+
use PHPUnit\Framework\TestCase;
8+
use Wrkflow\GetValue\Rules\HexColorRule;
9+
10+
class HexColorRuleTest extends TestCase
11+
{
12+
public function dataProvider(): array
13+
{
14+
return [
15+
[0.0, false],
16+
[1.0, false],
17+
[false, false],
18+
[true, false],
19+
[1, false],
20+
[4544, false],
21+
['12', false],
22+
['#1', false],
23+
['#FF', false],
24+
['test', false],
25+
[[], false],
26+
['red', false],
27+
['yellow', false],
28+
['#000', true],
29+
['#0000', true],
30+
['#00000', true],
31+
['#00000', true],
32+
['000', true],
33+
['0000', true],
34+
['00000', true],
35+
['00000', true],
36+
['#354D73', true],
37+
['#063971', true],
38+
['#F39F18', true],
39+
['#FFF', true],
40+
['#D84B20', true],
41+
];
42+
}
43+
44+
/**
45+
* @dataProvider dataProvider
46+
*/
47+
public function testPassesOnExisting(string|int|array|float|null|bool $arg, bool $expected): void
48+
{
49+
$this->assertEquals($expected, (new HexColorRule())->passes($arg));
50+
}
51+
}

0 commit comments

Comments
 (0)