|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Spatie\Color; |
|
4
|
|
|
|
|
5
|
|
|
class Rgb implements Color |
|
6
|
|
|
{ |
|
7
|
|
|
/** @var int */ |
|
8
|
|
|
protected $red, $green, $blue; |
|
|
|
|
|
|
9
|
|
|
|
|
10
|
|
View Code Duplication |
public function __construct(int $red, int $green, int $blue) |
|
|
|
|
|
|
11
|
|
|
{ |
|
12
|
|
|
Validate::rgbChannelValue($red, 'red'); |
|
13
|
|
|
Validate::rgbChannelValue($green, 'green'); |
|
14
|
|
|
Validate::rgbChannelValue($blue, 'blue'); |
|
15
|
|
|
|
|
16
|
|
|
$this->red = $red; |
|
17
|
|
|
$this->green = $green; |
|
18
|
|
|
$this->blue = $blue; |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
View Code Duplication |
public static function fromString(string $string) |
|
|
|
|
|
|
22
|
|
|
{ |
|
23
|
|
|
Validate::rgbColorString($string); |
|
24
|
|
|
|
|
25
|
|
|
$matches = null; |
|
26
|
|
|
preg_match('/rgb\((\d{1,3},\d{1,3},\d{1,3})\)/i', $string, $matches); |
|
27
|
|
|
|
|
28
|
|
|
list($red, $green, $blue) = explode(',', $matches[1]); |
|
29
|
|
|
|
|
30
|
|
|
return new static($red, $green, $blue); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
public function red(): int |
|
34
|
|
|
{ |
|
35
|
|
|
return $this->red; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
public function green(): int |
|
39
|
|
|
{ |
|
40
|
|
|
return $this->green; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
public function blue(): int |
|
44
|
|
|
{ |
|
45
|
|
|
return $this->blue; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
public function toHex(): Hex |
|
49
|
|
|
{ |
|
50
|
|
|
return new Hex( |
|
51
|
|
|
Convert::rgbChannelToHexChannel($this->red), |
|
52
|
|
|
Convert::rgbChannelToHexChannel($this->green), |
|
53
|
|
|
Convert::rgbChannelToHexChannel($this->blue) |
|
54
|
|
|
); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
public function toRgb(): Rgb |
|
58
|
|
|
{ |
|
59
|
|
|
return new Rgb($this->red, $this->green, $this->blue); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
public function toRgba(float $alpha = 1): Rgba |
|
63
|
|
|
{ |
|
64
|
|
|
return new Rgba($this->red, $this->green, $this->blue, $alpha); |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
public function __toString(): string |
|
68
|
|
|
{ |
|
69
|
|
|
return "rgb({$this->red},{$this->green},{$this->blue})"; |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|
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.