42 if (
$value ===
null && !defined(
'static::__default')) {
43 throw new Exception\InvalidEnumerationValueException(
44 sprintf(
'A value for enumeration "%s" is required if no __default is defined.', static::class),
53 throw new Exception\InvalidEnumerationValueException(
54 sprintf(
'Invalid value "%s" for enumeration "%s"',
$value, static::class),
68 $class = get_called_class();
70 if (isset(static::$enumConstants[$class])) {
74 $reflection = new \ReflectionClass($class);
75 $constants = $reflection->getConstants();
77 if (isset($constants[
'__default'])) {
78 $defaultValue = $constants[
'__default'];
79 unset($constants[
'__default']);
81 if (empty($constants)) {
82 throw new Exception\InvalidEnumerationValueException(
84 'No constants defined in enumeration "%s"',
90 foreach ($constants as $constant =>
$value) {
92 throw new Exception\InvalidEnumerationDefinitionException(
94 'Constant value "%s" of enumeration "%s" must be of type integer or string, got "%s" instead',
103 $constantValueCounts = array_count_values($constants);
104 arsort($constantValueCounts, SORT_NUMERIC);
105 $constantValueCount = current($constantValueCounts);
106 $constant = key($constantValueCounts);
107 if ($constantValueCount > 1) {
108 throw new Exception\InvalidEnumerationDefinitionException(
110 'Constant value "%s" of enumeration "%s" is not unique (defined %d times)',
118 if ($defaultValue !==
null) {
119 $constants[
'__default'] = $defaultValue;
121 static::$enumConstants[$class] = $constants;
133 $enumKey = array_search((
string)
$value, static::$enumConstants[static::class]);
134 if ($enumKey ===
false) {
135 throw new Exception\InvalidEnumerationValueException(
136 sprintf(
'Invalid value "%s" for enumeration "%s"',
$value, __CLASS__),
140 $this->value = static::$enumConstants[static::class][$enumKey];
152 foreach (static::$enumConstants[static::class] as $constantValue) {
153 if (
$value === (
string)$constantValue) {
168 public static function getConstants($include_default =
false)
170 static::loadValues();
172 if (!$include_default) {
186 if (!is_object(
$value) || get_class(
$value) !== static::class) {
221 $constants = array_flip(static::getConstants());
222 if (array_key_exists(
$value, $constants)) {
236 $name = static::getName(
$value);
237 return ucwords(strtolower(str_replace(
'_',
' ', $name)));