Completed
Push — master ( d7b920...15274c )
by ARCANEDEV
7s
created

HEXTrait   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 0
dl 0
loc 74
ccs 18
cts 18
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A hexToRgb() 0 4 1
A fromHexToRgb() 0 14 2
A rgbToHex() 0 4 1
A fromRgbToHex() 0 6 1
1
<?php namespace Arcanedev\Color\Converters;
2
3
/**
4
 * Trait     HEXTrait
5
 *
6
 * @package  Arcanedev\Color\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 (alias).
17
     *
18
     * @see    fromHexToRgb
19
     *
20
     * @param  string  $hex
21
     *
22
     * @return array
23
     */
24 16
    public static function hexToRgb($hex)
25
    {
26 16
        return (new self)->fromHexToRgb($hex);
27
    }
28
29
    /**
30
     * Convert a HEX color to an RGB array.
31
     *
32
     * @param  string  $hex
33
     *
34
     * @return array
35
     */
36 24
    public function fromHexToRgb($hex)
37
    {
38 24
        $value = str_replace('#', '', $hex);
39
40 24
        return array_map('hexdec', strlen($value) === 6 ? [
41 24
            substr($value, 0, 2), // RED
42 24
            substr($value, 2, 2), // GREEN
43 24
            substr($value, 4, 2), // BLUE
44 18
        ] : [
45 8
            str_repeat(substr($value, 0, 1), 2), // RED
46 8
            str_repeat(substr($value, 1, 1), 2), // GREEN
47 12
            str_repeat(substr($value, 2, 1), 2), // BLUE
48 18
        ]);
49
    }
50
51
    /**
52
     * Convert RGB values to a HEX color (alias).
53
     *
54
     * @see    fromRgbToHex
55
     *
56
     * @param  int  $red
57
     * @param  int  $green
58
     * @param  int  $blue
59
     *
60
     * @return string
61
     */
62 16
    public static function rgbToHex($red, $green, $blue)
63
    {
64 16
        return (new self)->fromRgbToHex($red, $green, $blue);
65
    }
66
67
    /**
68
     * Convert RGB values to a HEX color.
69
     *
70
     * @param  int  $red
71
     * @param  int  $green
72
     * @param  int  $blue
73
     *
74
     * @return string
75
     */
76
    public function fromRgbToHex($red, $green, $blue)
77
    {
78 24
        return '#' . implode('', array_map(function ($value) {
79 24
            return str_pad(dechex($value), 2, '0', STR_PAD_LEFT);
80 24
        }, [$red, $green, $blue]));
81
    }
82
}
83