Completed
Push — master ( 3f6bda...9e3353 )
by Joao
03:40
created

ColorHelper::adjustBrightness()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 22
rs 9.2
cc 3
eloc 12
nc 4
nop 2
1
<?php
2
3
namespace jlourenco\base\Helpers;
4
5
class ColorHelper {
6
7
    public static function adjustBrightness($hex, $steps) {
8
        // Steps should be between -255 and 255. Negative = darker, positive = lighter
9
        $steps = max(-255, min(255, $steps));
10
11
        // Normalize into a six character long hex string
12
        $hex = str_replace('#', '', $hex);
13
        if (strlen($hex) == 3) {
14
            $hex = str_repeat(substr($hex,0,1), 2).str_repeat(substr($hex,1,1), 2).str_repeat(substr($hex,2,1), 2);
15
        }
16
17
        // Split into three parts: R, G and B
18
        $color_parts = str_split($hex, 2);
19
        $return = '#';
20
21
        foreach ($color_parts as $color) {
22
            $color   = hexdec($color); // Convert to decimal
23
            $color   = max(0,min(255,$color + $steps)); // Adjust color
24
            $return .= str_pad(dechex($color), 2, '0', STR_PAD_LEFT); // Make two char hex code
25
        }
26
27
        return $return;
28
    }
29
30
}
31