Completed
Push — master ( b858c3...697839 )
by Nicholas
03:33
created

css::best()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 2
Bugs 0 Features 2
Metric Value
dl 0
loc 7
ccs 0
cts 5
cp 0
rs 9.4285
c 2
b 0
f 2
cc 3
eloc 5
nc 2
nop 1
crap 12
1
<?php
2
3
namespace projectcleverweb\color;
4
5
class css {
6
	
7
	/**
8
	 * Force alpha value to be present where possible.
9
	 * @var boolean
10
	 */
11
	public static $force_alpha = FALSE;
12
	
13
	/**
14
	 * Choose the best way to represent the color as a CSS value. Will use either
15
	 * a hex or rgba value depending on the alpha value.
16
	 * 
17
	 * @param  mixed $color The color 
18
	 * @return string       The CSS value
19
	 */
20
	public static function best($color) {
21
		static::_color_instance($color);
22
		if ($color->alpha == 1.0 && !static::$force_alpha) {
23
			return static::hex($color->rgb['r'], $color->rgb['g'], $color->rgb['b']);
24
		}
25
		return static::rgb($color->rgb['r'], $color->rgb['g'], $color->rgb['b'], $color->alpha);
26
	}
27
	
28
	/**
29
	 * Force $color to be an instance of color
30
	 * 
31
	 * @param  mixed &$color The color
32
	 * @return void
33
	 */
34
	protected static function _color_instance(&$color) {
35
		if (!is_a($color, __CLASS__)) {
36
			$color = new color($color);
37
		}
38
	}
39
	
40
	/**
41
	 * Convert and RGB value to a CSS hex string
42
	 * 
43
	 * @param  float  $r The red value
44
	 * @param  float  $g The green value
45
	 * @param  float  $b The blue value
46
	 * @return string    The CSS string
47
	 */
48
	public static function hex(float $r, float $g, float $b) {
49
		return '#'.generate::rgb_to_hex($r, $g, $b);
50
	}
51
	
52
	/**
53
	 * Convert and RGB value to a CSS rgb or rgba string
54
	 * 
55
	 * @param  float  $r The red value
56
	 * @param  float  $g The green value
57
	 * @param  float  $b The blue value
58
	 * @return string    The CSS string
59
	 */
60
	public static function rgb(float $r, float $g, float $b, float $a = 1.0) {
61
		if ($a == 1.0 && !static::$force_alpha) {
62
			return sprintf('rgb(%s,%s,%s)', $r, $g, $b);
63
		}
64
		return sprintf('rgba(%s,%s,%s,%s)', $r, $g, $b, $a);
65
	}
66
	
67
	/**
68
	 * Convert and HSL value to a CSS hsl or hsla string
69
	 * 
70
	 * @param  float  $h The hue value
71
	 * @param  float  $s The saturation value
72
	 * @param  float  $l The light value
73
	 * @return string    The CSS string
74
	 */
75
	public static function hsl(float $h, float $s, float $l, float $a = 1.0) {
76
		if ($a == 1.0 && !static::$force_alpha) {
77
			return sprintf('hsl(%s,%s,%s)', $h, $s, $l);
78
		}
79
		return sprintf('hsla(%s,%s,%s,%s)', $h, $s, $l, $a);
80
	}
81
}
82