From 16b507daababea99cbea4bf56380d86cf547f6b5 Mon Sep 17 00:00:00 2001 From: MK Date: Mon, 2 Nov 2020 22:33:07 -0500 Subject: [PATCH 1/3] Add option to validate transparent color codes --- src/Hex.php | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/Hex.php b/src/Hex.php index 16d356a..6f8eff5 100644 --- a/src/Hex.php +++ b/src/Hex.php @@ -11,9 +11,16 @@ class Hex implements Rule */ protected $forceFull; - public function __construct($forceFull = false) + /** + * @var bool + */ + protected $allowAlpha; + + public function __construct($forceFull = false, $allowAlpha = false) { $this->forceFull = $forceFull; + + $this->allowAlpha = $allowAlpha; } /** @@ -27,11 +34,20 @@ public function __construct($forceFull = false) public function passes($attribute, $value) { $pattern = '/^#([a-fA-F0-9]{6}'; - + if (!$this->forceFull) { $pattern .= '|[a-fA-F0-9]{3}'; } + if ($this->allowAlpha) { + $pattern .= '|[a-fA-F0-9]{8}'; + + if (!$this->forceFull) { + $pattern .= '|[a-fA-F0-9]{4}'; + } + } + + $pattern .= ')$/'; return (bool) preg_match($pattern, $value); From 42dd9450dbbaba96e243c67cd247f22c7d845060 Mon Sep 17 00:00:00 2001 From: MK Date: Mon, 2 Nov 2020 22:38:12 -0500 Subject: [PATCH 2/3] add tests for alpha check --- tests/Feature/HexTest.php | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tests/Feature/HexTest.php b/tests/Feature/HexTest.php index 2f0ac1c..dc2fbfc 100644 --- a/tests/Feature/HexTest.php +++ b/tests/Feature/HexTest.php @@ -37,4 +37,20 @@ public function three_characters_with_hash() $this->assertTrue($this->validator('#fff', false)->passes()); // full } + + public function eight_characters_with_hash() + { + $this->assertTrue($this->validator('#ff008000')->fails()); + $this->assertTrue($this->validator('#fg00800g', true, true)->fails()); + $this->assertTrue($this->validator('#ff008000', true, true)->passes()); + } + + /** @test */ + public function four_characters_with_hash() + { + $this->assertTrue($this->validator('#ffff', true, true)->passes()); + $this->assertTrue($this->validator('#ffff', true, false)->fails()); + $this->assertTrue($this->validator('#gggg', true, true)->fails()); + $this->assertTrue($this->validator('#ffff', false, true)->passes()); + } } From d48af17f4e91aaea14dd04bc6f65ab488ffb84c8 Mon Sep 17 00:00:00 2001 From: MK Date: Mon, 2 Nov 2020 22:39:57 -0500 Subject: [PATCH 3/3] fix whitespace --- src/Hex.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Hex.php b/src/Hex.php index 6f8eff5..3ab9b20 100644 --- a/src/Hex.php +++ b/src/Hex.php @@ -34,7 +34,7 @@ public function __construct($forceFull = false, $allowAlpha = false) public function passes($attribute, $value) { $pattern = '/^#([a-fA-F0-9]{6}'; - + if (!$this->forceFull) { $pattern .= '|[a-fA-F0-9]{3}'; } @@ -47,7 +47,6 @@ public function passes($attribute, $value) } } - $pattern .= ')$/'; return (bool) preg_match($pattern, $value);