This repository was archived by the owner on Apr 9, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnum.php
More file actions
107 lines (94 loc) · 2.17 KB
/
Copy pathEnum.php
File metadata and controls
107 lines (94 loc) · 2.17 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
/**
* Copyright (C) GrizzIT, Inc. All rights reserved.
* See LICENSE for license details.
*/
namespace Ulrack\Enum;
use ReflectionClass;
abstract class Enum
{
/**
* Contains a backup of the searched class constant associations.
*
* @var array
*/
private static $classConstants;
/**
* Contains the value of the enum.
*
* @var mixed
*/
private $value;
/**
* Constructor
*
* @param mixed $value
*/
public function __construct($value)
{
$this->value = $value;
}
/**
* Returns the value of the enum.
*
* @return string
*/
public function __toString(): string
{
return $this->value;
}
/**
* Retrieves the ordinal value of the enum.
*
* @param mixed $value
*
* @return string
*/
public static function getOrdinal($value): string
{
self::mapConstants(static::class);
return self::$classConstants[static::class]['ordinal'][$value];
}
/**
* Retrieves all options from the enum.
*
* @method getOptions
*
* @return array
*/
public static function getOptions(): array
{
self::mapConstants(static::class);
return self::$classConstants[static::class]['constant'];
}
/**
* Retrieves the value of the enum.
*
* @param string $name
* @param array $arguments
*
* @return mixed
*/
public static function __callStatic(string $name, array $arguments)
{
self::mapConstants(static::class);
return new static(
self::$classConstants[static::class]['constant'][$name]
);
}
/**
* Maps the constant and ordinal values to their class.
*
* @param string $class
*
* @return void
*/
private static function mapConstants(string $class): void
{
if (!isset(self::$classConstants[static::class])) {
$constants = (new ReflectionClass($class))->getConstants();
self::$classConstants[$class]['constant'] = $constants;
self::$classConstants[$class]['ordinal'] = array_flip($constants);
}
}
}