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
|
|
|
|