Skip to content

Commit 1e7ab24

Browse files
authored
Merge pull request #9 from kohenkatz/patch-1
Add option to allow alpha transparency as 4 or 8 characters
2 parents 2222622 + d48af17 commit 1e7ab24

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

src/Hex.php

+16-1
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,16 @@ class Hex implements Rule
1111
*/
1212
protected $forceFull;
1313

14-
public function __construct($forceFull = false)
14+
/**
15+
* @var bool
16+
*/
17+
protected $allowAlpha;
18+
19+
public function __construct($forceFull = false, $allowAlpha = false)
1520
{
1621
$this->forceFull = $forceFull;
22+
23+
$this->allowAlpha = $allowAlpha;
1724
}
1825

1926
/**
@@ -32,6 +39,14 @@ public function passes($attribute, $value)
3239
$pattern .= '|[a-fA-F0-9]{3}';
3340
}
3441

42+
if ($this->allowAlpha) {
43+
$pattern .= '|[a-fA-F0-9]{8}';
44+
45+
if (!$this->forceFull) {
46+
$pattern .= '|[a-fA-F0-9]{4}';
47+
}
48+
}
49+
3550
$pattern .= ')$/';
3651

3752
return (bool) preg_match($pattern, $value);

tests/Feature/HexTest.php

+16
Original file line numberDiff line numberDiff line change
@@ -37,4 +37,20 @@ public function three_characters_with_hash()
3737

3838
$this->assertTrue($this->validator('#fff', false)->passes()); // full
3939
}
40+
41+
public function eight_characters_with_hash()
42+
{
43+
$this->assertTrue($this->validator('#ff008000')->fails());
44+
$this->assertTrue($this->validator('#fg00800g', true, true)->fails());
45+
$this->assertTrue($this->validator('#ff008000', true, true)->passes());
46+
}
47+
48+
/** @test */
49+
public function four_characters_with_hash()
50+
{
51+
$this->assertTrue($this->validator('#ffff', true, true)->passes());
52+
$this->assertTrue($this->validator('#ffff', true, false)->fails());
53+
$this->assertTrue($this->validator('#gggg', true, true)->fails());
54+
$this->assertTrue($this->validator('#ffff', false, true)->passes());
55+
}
4056
}

0 commit comments

Comments
 (0)