1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Breadthe\PhpContrast; |
4
|
|
|
|
5
|
|
|
class HexColor implements Color |
6
|
|
|
{ |
7
|
|
|
public $hex; |
8
|
|
|
public $name; |
9
|
|
|
|
10
|
|
|
public function __construct(string $hex, string $name = null) |
11
|
|
|
{ |
12
|
|
|
$this->hex = $this->normalize($hex); |
13
|
|
|
$this->name = $name; |
14
|
|
|
} |
15
|
|
|
|
16
|
|
|
public static function make(string $hex, string $name = null): self |
17
|
|
|
{ |
18
|
|
|
return new static($hex, $name); |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
public static function random(): self |
22
|
|
|
{ |
23
|
|
|
return new static(self::randomColor()); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* '#abc' or 'abc' => '#aabbcc' |
28
|
|
|
* '#abcdef' or 'abcdef' => '#abcdef'. |
29
|
|
|
*/ |
30
|
|
|
protected function normalize(string $hexColor) |
31
|
|
|
{ |
32
|
|
|
// '#abcdef' or 'abcdef' |
33
|
|
|
if (preg_match('/^\s*#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})\s*$/i', $hexColor, $matches)) { |
34
|
|
|
return sprintf('#%s%s%s', $matches[1], $matches[2], $matches[3]); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
// '#abc' or 'abc' |
38
|
|
|
if (preg_match('/^\s*#?([0-9a-f])([0-9a-f])([0-9a-f])\s*$/i', $hexColor, $matches)) { |
39
|
|
|
return sprintf('#%s%s%s', str_repeat($matches[1], 2), str_repeat($matches[2], 2), |
40
|
|
|
str_repeat($matches[3], 2)); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
// TODO throw |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @see https://stackoverflow.com/questions/5614530/generating-a-random-hex-color-code-with-php |
48
|
|
|
*/ |
49
|
|
|
protected static function randomColor() |
50
|
|
|
{ |
51
|
|
|
return static::randomColorPart().static::randomColorPart().static::randomColorPart(); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
protected static function randomColorPart() |
55
|
|
|
{ |
56
|
|
|
return str_pad(dechex(mt_rand(0, 255)), 2, '0', STR_PAD_LEFT); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|