1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace EaselDrawing; |
4
|
|
|
|
5
|
|
|
class Color |
6
|
|
|
{ |
7
|
|
|
private $red; |
8
|
|
|
private $green; |
9
|
|
|
private $blue; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Color constructor. |
13
|
|
|
* @param $red |
14
|
|
|
* @param $green |
15
|
|
|
* @param $blue |
16
|
|
|
*/ |
17
|
|
|
public function __construct(int $red, int $green, int $blue) |
18
|
|
|
{ |
19
|
|
|
$this->red = max(0, min(255, $red)); |
20
|
|
|
$this->green = max(0, min(255, $green)); |
21
|
|
|
$this->blue = max(0, min(255, $blue)); |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
public static function newFromArray(array $values) |
25
|
|
|
{ |
26
|
|
|
$rgb = [0, 0, 0]; |
27
|
|
|
$values = array_values($values); |
28
|
|
|
foreach (range(0, 2) as $index) { |
29
|
|
|
if (isset($values[$index])) { |
30
|
|
|
$rgb[$index] = $values[$index]; |
31
|
|
|
} |
32
|
|
|
} |
33
|
|
|
return new Color($rgb[0], $rgb[1], $rgb[2]); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public static function newFromString(string $value) |
37
|
|
|
{ |
38
|
|
|
$value = strtolower(substr($value, 0, 6)); |
39
|
|
|
if (strlen($value) == 3) { |
40
|
|
|
$value = substr($value, 0, 1) . substr($value, 0, 1) |
41
|
|
|
. substr($value, 1, 1) . substr($value, 1, 1) |
42
|
|
|
. substr($value, 2, 1) . substr($value, 2, 1); |
43
|
|
|
} |
44
|
|
|
if (! preg_match('/^[[:xdigit:]]{6}$/', $value)) { |
45
|
|
|
throw new \InvalidArgumentException('A color must contain 3 or 6 hexadecimal characters'); |
46
|
|
|
} |
47
|
|
|
$rgb = []; |
48
|
|
|
foreach (range(0, 2) as $index) { |
49
|
|
|
$rgb[$index] = substr($value, $index * 2, 2); |
50
|
|
|
} |
51
|
|
|
return new Color(hexdec($rgb[0]), hexdec($rgb[1]), hexdec($rgb[2])); |
|
|
|
|
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function getRed(): int |
55
|
|
|
{ |
56
|
|
|
return $this->red; |
|
|
|
|
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function getGreen(): int |
60
|
|
|
{ |
61
|
|
|
return $this->green; |
|
|
|
|
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
public function getBlue(): int |
65
|
|
|
{ |
66
|
|
|
return $this->blue; |
|
|
|
|
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
public function getRGB() |
70
|
|
|
{ |
71
|
|
|
return [$this->red, $this->blue, $this->green]; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
public function getHex(): string |
75
|
|
|
{ |
76
|
|
|
return $this->intToHex($this->red) |
77
|
|
|
. $this->intToHex($this->green) |
78
|
|
|
. $this->intToHex($this->blue); |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
private function intToHex($value): string |
82
|
|
|
{ |
83
|
|
|
return sprintf('%02s', dechex($value)); |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|