-
Notifications
You must be signed in to change notification settings - Fork 456
Expand file tree
/
Copy pathHexToRgb.php
More file actions
70 lines (61 loc) · 1.87 KB
/
HexToRgb.php
File metadata and controls
70 lines (61 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
namespace SimpleSoftwareIO\QrCode;
use InvalidArgumentException;
class HexToRgb
{
public int $red;
public int $green;
public int $blue;
public function __construct(public string $hex, public mixed $alpha = false)
{
if ($this->validateHex($hex) === false) {
throw new InvalidArgumentException('Invalid hex value, not a hex code');
}
$this->hexToRgb($hex, $alpha);
}
public function toRGBArray(): array
{
return [
$this->red,
$this->green,
$this->blue,
];
}
/**
* Validate a hex code. Returns true if valid, false if not.
* Taken from Drupal.
* @see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Component%21Utility%21Color.php/function/Color%3A%3AvalidateHex/8.2.x
*
* @param string $hex
*
* @return bool
*/
private function validateHex(string $hex): bool
{
return preg_match('/^[#]?([0-9a-fA-F]{3}){1,2}$/', $hex) === 1;
}
/**
* Convert a hex code to RGB.
*
* @see https://stackoverflow.com/questions/15202079/convert-hex-color-to-rgb-values-in-php
*
* @param string $hex
* @param mixed $alpha
*
* @return void
*/
private function hexToRgb(string $hex, mixed $alpha = false): void
{
$hex = str_replace('#', '', $hex);
$length = strlen($hex);
$this->red = hexdec($length == 6 ? substr($hex, 0, 2) : ($length == 3 ? str_repeat(substr($hex, 0, 1),
2) : 0));
$this->green = hexdec($length == 6 ? substr($hex, 2, 2) : ($length == 3 ? str_repeat(substr($hex, 1, 1),
2) : 0));
$this->blue = hexdec($length == 6 ? substr($hex, 4, 2) : ($length == 3 ? str_repeat(substr($hex, 2, 1),
2) : 0));
if ($alpha) {
$this->alpha = $alpha;
}
}
}