Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions src/HexColorAlpha.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php

declare(strict_types = 1);

namespace SmartEmailing\Types;

use Nette\Utils\Strings;
use SmartEmailing\Types\Comparable\ComparableInterface;
use SmartEmailing\Types\Comparable\StringComparableTrait;
use SmartEmailing\Types\ExtractableTraits\StringExtractableTrait;

final class HexColorAlpha implements ToStringInterface, ComparableInterface
{

use StringExtractableTrait;
use ToStringTrait;
use StringComparableTrait;

private string $value;

public function __construct(
string $value
)
{
$value = $this->preprocess($value);

if (!$this->isValid($value)) {
throw new InvalidTypeException('Invalid hex color string: ' . $value);
}

$value = $this->processAlpha($value);

$this->value = $value;
}

public function getValue(): string
{
return $this->value;
}

private function isValid(
string $value
): bool
{
return (bool) \preg_match('#^\#([A-F0-9]{3,4}|[A-F0-9]{6}|[A-F0-9]{8})\z#', $value);
}

private function preprocess(
string $value
): string
{
return Strings::upper($value);
}

private function processAlpha(
string $value
): string
{
$hex = \ltrim($value, '#');
$length = \strlen($hex);

return match ($length) {
8, 4 => '#' . $hex,
6 => '#' . $hex . 'FF',
3 => '#' . $hex . 'F',
default => throw new InvalidTypeException('Invalid hex color length (' . $length . '): ' . $value),
};
}

}
54 changes: 54 additions & 0 deletions tests/HexColorAlphaTest.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

declare(strict_types = 1);

namespace SmartEmailing\Types;

use Tester\Assert;
use Tester\TestCase;

require __DIR__ . '/bootstrap.php';

final class HexColorAlphaTest extends TestCase
{

public function test1(): void
{
$invalidValues = [
'fff',
'00668',
'#00668',
'#ff',
'#zzzzzz',
'skakalpes',
'#ffffffffff',
];

foreach ($invalidValues as $invalidValue) {
Assert::throws(
static function () use ($invalidValue): void {
HexColorAlpha::from($invalidValue);
},
InvalidTypeException::class
);
}

$validValues = [
'#FFFFFF',
'#FFF',
'#FFFF',
'#00FF00FF',
'#000F',
];

foreach ($validValues as $validValue) {
HexColorAlpha::from($validValue);
}

$hexColor = HexColorAlpha::from('#fff');
Assert::equal('#FFFF', $hexColor->getValue());
}

}

(new HexColorAlphaTest())->run();