|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Spatie\Color; |
|
4
|
|
|
|
|
5
|
|
|
class Hex implements Color |
|
6
|
|
|
{ |
|
7
|
|
|
/** @var string */ |
|
8
|
|
|
protected $red, $green, $blue; |
|
|
|
|
|
|
9
|
|
|
|
|
10
|
|
|
public function __construct(string $red, string $green, string $blue) |
|
11
|
|
|
{ |
|
12
|
|
|
Validate::hexChannelValue($red, 'red'); |
|
|
|
|
|
|
13
|
|
|
Validate::hexChannelValue($green, 'green'); |
|
|
|
|
|
|
14
|
|
|
Validate::hexChannelValue($blue, 'blue'); |
|
|
|
|
|
|
15
|
|
|
|
|
16
|
|
|
$this->red = strtolower($red); |
|
17
|
|
|
$this->green = strtolower($green); |
|
18
|
|
|
$this->blue = strtolower($blue); |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
public static function fromString(string $string) |
|
22
|
|
|
{ |
|
23
|
|
|
Validate::hexColorString($string); |
|
24
|
|
|
|
|
25
|
|
|
list($red, $green, $blue) = str_split(ltrim($string, '#'), 2); |
|
26
|
|
|
|
|
27
|
|
|
return new static($red, $green, $blue); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
public function red(): string |
|
31
|
|
|
{ |
|
32
|
|
|
return $this->red; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
public function green(): string |
|
36
|
|
|
{ |
|
37
|
|
|
return $this->green; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
public function blue(): string |
|
41
|
|
|
{ |
|
42
|
|
|
return $this->blue; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
public function toHex(): Hex |
|
46
|
|
|
{ |
|
47
|
|
|
return new self($this->red, $this->green, $this->blue); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
public function toRgb(): Rgb |
|
51
|
|
|
{ |
|
52
|
|
|
return new Rgb( |
|
53
|
|
|
Convert::hexChannelToRgbChannel($this->red), |
|
54
|
|
|
Convert::hexChannelToRgbChannel($this->green), |
|
55
|
|
|
Convert::hexChannelToRgbChannel($this->blue) |
|
56
|
|
|
); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
public function toRgba(float $alpha = 1): Rgba |
|
60
|
|
|
{ |
|
61
|
|
|
return $this->toRgb()->toRgba($alpha); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
public function __toString(): string |
|
65
|
|
|
{ |
|
66
|
|
|
return "#{$this->red}{$this->green}{$this->blue}"; |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|
Only declaring a single property per statement allows you to later on add doc comments more easily.
It is also recommended by PSR2, so it is a common style that many people expect.