xref: /webtrees/app/Statistics/Service/ColorService.php (revision 4fbeb707df82fa5025e6110f443695700edd846c)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2019 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16declare(strict_types=1);
17
18namespace Fisharebest\Webtrees\Statistics\Service;
19
20/**
21 * Functions for managing and manipulating colors.
22 */
23class ColorService
24{
25    /**
26     * Interpolates the number of color steps between a given start and end color.
27     *
28     * @param string $startColor The start color
29     * @param string $endColor   The end color
30     * @param int    $steps      The number of steps to interpolate
31     *
32     * @return array
33     */
34    public function interpolateRgb(string $startColor, string $endColor, int $steps): array
35    {
36        if (!$steps) {
37            return [];
38        }
39
40        $s       = $this->hexToRgb($startColor);
41        $e       = $this->hexToRgb($endColor);
42        $colors  = [];
43        $factorR = ($e[0] - $s[0]) / $steps;
44        $factorG = ($e[1] - $s[1]) / $steps;
45        $factorB = ($e[2] - $s[2]) / $steps;
46
47        for ($x = 1; $x < $steps; ++$x) {
48            $colors[] = $this->rgbToHex(
49                (int) round($s[0] + ($factorR * $x)),
50                (int) round($s[1] + ($factorG * $x)),
51                (int) round($s[2] + ($factorB * $x))
52            );
53        }
54
55        $colors[] = $this->rgbToHex($e[0], $e[1], $e[2]);
56
57        return $colors;
58    }
59
60    /**
61     * Converts the color values to the HTML hex representation.
62     *
63     * @param int $r The red color value
64     * @param int $g The green color value
65     * @param int $b The blue color value
66     *
67     * @return string
68     */
69    private function rgbToHex(int $r, int $g, int $b): string
70    {
71        return sprintf('#%02x%02x%02x', $r, $g, $b);
72    }
73
74    /**
75     * Converts the HTML color hex representation to an array of color values.
76     *
77     * @param string $hex The HTML hex color code
78     *
79     * @return array
80     */
81    private function hexToRgb(string $hex): array
82    {
83        return array_map('hexdec', str_split(ltrim($hex, '#'), 2));
84    }
85}
86