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

HEXTrait   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 3
lcom 0
cbo 0
dl 0
loc 44
ccs 14
cts 14
cp 1
rs 10
c 1
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A hexToRgb() 0 14 2
A rgbToHex() 0 6 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