-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathColor.php
More file actions
74 lines (60 loc) · 1.62 KB
/
Color.php
File metadata and controls
74 lines (60 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
namespace Slutsky\EnumExample;
use BadMethodCallException;
use InvalidArgumentException;
/**
* @method static Color red()
* @method static Color green()
* @method static Color blue()
* @method static Color cyan()
* @method static Color magenta()
* @method static Color yellow()
* @method static Color black()
*/
class Color
{
public const COLORS = [
'red',
'green',
'blue',
'cyan',
'magenta',
'yellow',
'black',
];
private string $value;
private function __construct(string $value)
{
$this->value = $value;
}
private function __clone() { }
public function __toString(): string
{
return $this->value;
}
private static $instances = [];
public static function from($value): self
{
if (!in_array($value, self::COLORS)) {
throw new InvalidArgumentException(sprintf(
"Wrong color value: '$value'. Expected one from: '%s'.",
implode("', '", self::COLORS)
));
}
if (!array_key_exists($value, self::$instances)) {
self::$instances[$value] = new self($value);
}
return self::$instances[$value];
}
public static function __callStatic($name, $arguments)
{
$value = strtolower($name);
if (!in_array($value, self::COLORS)) {
throw new BadMethodCallException("Method '$name' not found.");
}
if (count($arguments) > 0) {
throw new InvalidArgumentException("Method '$name' expected no arguments.");
}
return self::from($value);
}
}