Skip to content

Commit

Permalink
Merge pull request #9 from kohenkatz/patch-1
Browse files Browse the repository at this point in the history
Add option to allow alpha transparency as 4 or 8 characters
  • Loading branch information
ssx authored Feb 8, 2022
2 parents 2222622 + d48af17 commit 1e7ab24
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/Hex.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand All @@ -32,6 +39,14 @@ public function passes($attribute, $value)
$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);
Expand Down
16 changes: 16 additions & 0 deletions tests/Feature/HexTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
}

0 comments on commit 1e7ab24

Please sign in to comment.