1<?php
2declare(strict_types = 1);
3
4namespace BaconQrCode\Renderer\Color;
5
6use BaconQrCode\Exception;
7
8final class Rgb implements ColorInterface
9{
10    /**
11     * @var int
12     */
13    private $red;
14
15    /**
16     * @var int
17     */
18    private $green;
19
20    /**
21     * @var int
22     */
23    private $blue;
24
25    /**
26     * @param int $red the red amount of the color, 0 to 255
27     * @param int $green the green amount of the color, 0 to 255
28     * @param int $blue the blue amount of the color, 0 to 255
29     */
30    public function __construct(int $red, int $green, int $blue)
31    {
32        if ($red < 0 || $red > 255) {
33            throw new Exception\InvalidArgumentException('Red must be between 0 and 255');
34        }
35
36        if ($green < 0 || $green > 255) {
37            throw new Exception\InvalidArgumentException('Green must be between 0 and 255');
38        }
39
40        if ($blue < 0 || $blue > 255) {
41            throw new Exception\InvalidArgumentException('Blue must be between 0 and 255');
42        }
43
44        $this->red = $red;
45        $this->green = $green;
46        $this->blue = $blue;
47    }
48
49    public function getRed() : int
50    {
51        return $this->red;
52    }
53
54    public function getGreen() : int
55    {
56        return $this->green;
57    }
58
59    public function getBlue() : int
60    {
61        return $this->blue;
62    }
63
64    public function toRgb() : Rgb
65    {
66        return $this;
67    }
68
69    public function toCmyk() : Cmyk
70    {
71        $c = 1 - ($this->red / 255);
72        $m = 1 - ($this->green / 255);
73        $y = 1 - ($this->blue / 255);
74        $k = min($c, $m, $y);
75
76        return new Cmyk(
77            (int) (100 * ($c - $k) / (1 - $k)),
78            (int) (100 * ($m - $k) / (1 - $k)),
79            (int) (100 * ($y - $k) / (1 - $k)),
80            (int) (100 * $k)
81        );
82    }
83
84    public function toGray() : Gray
85    {
86        return new Gray((int) (($this->red * 0.21 + $this->green * 0.71 + $this->blue * 0.07) / 2.55));
87    }
88}
89