diff --git a/README.md b/README.md index ee171ff..7cda9ed 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ Your code will be unbreakable and your IDE will love it. + [Domain](#domain) + [Hex 32](#hex-32) + [Hex Color](#hex-color) + + [Hex Color Alpha](#hex-color-alpha) + [GUID](#guid) + [IP address](#ip-address) + [URL](#url) @@ -229,6 +230,13 @@ Lowercased 32-characters long hexadecimal string useful as container for MD5 or Uppercased 7-characters long string useful as container for color. (`#006EDB`) +### Hex color alpha + +`SmartEmailing\Types\HexColorAlpha` + +Uppercased 9-character long string useful as a container for color with an alpha channel (transparency). (`#FFFFFFFF`) + +If you provide a standard 6-digit hex color (e.g., `#000000`), it will be automatically converted by appending FF for 100% opacity (`#000000FF`). ### GUID diff --git a/src/HexColorAlpha.php b/src/HexColorAlpha.php new file mode 100644 index 0000000..b902a64 --- /dev/null +++ b/src/HexColorAlpha.php @@ -0,0 +1,70 @@ +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), + }; + } + +} diff --git a/tests/HexColorAlphaTest.phpt b/tests/HexColorAlphaTest.phpt new file mode 100644 index 0000000..b96e3c0 --- /dev/null +++ b/tests/HexColorAlphaTest.phpt @@ -0,0 +1,54 @@ +getValue()); + } + +} + +(new HexColorAlphaTest())->run();