Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
94.74% |
18 / 19 |
|
85.71% |
6 / 7 |
CRAP | |
0.00% |
0 / 1 |
| RgbColor | |
94.74% |
18 / 19 |
|
85.71% |
6 / 7 |
14.03 | |
0.00% |
0 / 1 |
| __construct | |
83.33% |
5 / 6 |
|
0.00% |
0 / 1 |
7.23 | |||
| fromInt | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| fromHex | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
2 | |||
| toCmyk | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| toGray | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| toArray | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| getColorSpace | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Phpdftk\Color; |
| 6 | |
| 7 | /** |
| 8 | * RGB color with components in 0.0–1.0 range — maps to PDF DeviceRGB. |
| 9 | * |
| 10 | * Factory methods `fromInt()` and `fromHex()` accept the more common |
| 11 | * 0–255 and #RRGGBB formats and normalize to the PDF float range. |
| 12 | */ |
| 13 | final class RgbColor implements ColorInterface |
| 14 | { |
| 15 | public function __construct( |
| 16 | public readonly float $r, |
| 17 | public readonly float $g, |
| 18 | public readonly float $b, |
| 19 | ) { |
| 20 | if ($r < 0.0 || $r > 1.0) { |
| 21 | throw new \InvalidArgumentException("Red value must be 0.0–1.0, got $r"); |
| 22 | } |
| 23 | if ($g < 0.0 || $g > 1.0) { |
| 24 | throw new \InvalidArgumentException("Green value must be 0.0–1.0, got $g"); |
| 25 | } |
| 26 | if ($b < 0.0 || $b > 1.0) { |
| 27 | throw new \InvalidArgumentException("Blue value must be 0.0–1.0, got $b"); |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | public static function fromInt(int $r, int $g, int $b): self |
| 32 | { |
| 33 | return new self($r / 255.0, $g / 255.0, $b / 255.0); |
| 34 | } |
| 35 | |
| 36 | public static function fromHex(string $hex): self |
| 37 | { |
| 38 | $hex = ltrim($hex, '#'); |
| 39 | if (strlen($hex) !== 6) { |
| 40 | throw new \InvalidArgumentException("Invalid hex color: $hex"); |
| 41 | } |
| 42 | return self::fromInt( |
| 43 | hexdec(substr($hex, 0, 2)), |
| 44 | hexdec(substr($hex, 2, 2)), |
| 45 | hexdec(substr($hex, 4, 2)), |
| 46 | ); |
| 47 | } |
| 48 | |
| 49 | public function toCmyk(): CmykColor |
| 50 | { |
| 51 | return ColorConverter::rgbToCmyk($this); |
| 52 | } |
| 53 | |
| 54 | public function toGray(): GrayColor |
| 55 | { |
| 56 | return ColorConverter::rgbToGray($this); |
| 57 | } |
| 58 | |
| 59 | /** @return array<int, float> */ |
| 60 | public function toArray(): array |
| 61 | { |
| 62 | return [$this->r, $this->g, $this->b]; |
| 63 | } |
| 64 | |
| 65 | public function getColorSpace(): string |
| 66 | { |
| 67 | return 'DeviceRGB'; |
| 68 | } |
| 69 | } |