Completed
Pull Request — master (#1)
by ARCANEDEV
09:00
created

HEXTrait::rgbToHex()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
c 1
b 0
f 0
cc 1
eloc 4
nc 1
nop 3
crap 1
1
<?php namespace Arcanedev\Color\Helpers\Converters;
2
3
/**
4
 * Class     HEXTrait
5
 *
6
 * @package  Arcanedev\Color\Helpers\Converters
7
 * @author   ARCANEDEV <[email protected]>
8
 */
9
trait HEXTrait
10
{
11
    /* ------------------------------------------------------------------------------------------------
12
     |  Main Functions
13
     | ------------------------------------------------------------------------------------------------
14
     */
15
    /**
16
     * Convert a HEX color to an RGB array.
17
     *
18
     * @param  string  $hex
19
     *
20
     * @return array
21
     */
22 24
    public static function hexToRgb($hex)
23
    {
24 24
        $value = str_replace('#', '', $hex);
25
26 24
        return array_map('hexdec', strlen($value) === 6 ? [
27 24
            substr($value, 0, 2), // RED
28 24
            substr($value, 2, 2), // GREEN
29 24
            substr($value, 4, 2), // BLUE
30 12
        ] : [
31 8
            str_repeat(substr($value, 0, 1), 2), // RED
32 8
            str_repeat(substr($value, 1, 1), 2), // GREEN
33 16
            str_repeat(substr($value, 2, 1), 2), // BLUE
34 12
        ]);
35
    }
36
37
    /**
38
     * Convert RGB values to a HEX color.
39
     *
40
     * @param  int  $red
41
     * @param  int  $green
42
     * @param  int  $blue
43
     *
44
     * @return string
45
     */
46
    public static function rgbToHex($red, $green, $blue)
47
    {
48 24
        return '#' . implode('', array_map(function ($value) {
49 24
            return str_pad(dechex($value), 2, '0', STR_PAD_LEFT);
50 24
        }, [$red, $green, $blue]));
51
    }
52
}
53