forked from BenSampo/laravel-enum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEnum.php
586 lines (515 loc) · 14.1 KB
/
Enum.php
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
<?php
namespace BenSampo\Enum;
use ReflectionClass;
use JsonSerializable;
use Illuminate\Support\Str;
use BenSampo\Enum\Casts\EnumCast;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Traits\Macroable;
use BenSampo\Enum\Contracts\EnumContract;
use BenSampo\Enum\Contracts\LocalizedEnum;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Database\Eloquent\Castable;
use BenSampo\Enum\Exceptions\InvalidEnumKeyException;
use BenSampo\Enum\Exceptions\InvalidEnumMemberException;
abstract class Enum implements EnumContract, Castable, Arrayable, JsonSerializable
{
use Macroable {
__callStatic as macroCallStatic;
__call as macroCall;
}
/**
* The value of one of the enum members.
*
* @var mixed
*/
public $value;
/**
* The key of one of the enum members.
*
* @var mixed
*/
public $key;
/**
* The description of one of the enum members.
*
* @var mixed
*/
public $description;
/**
* Constants cache.
*
* @var array
*/
protected static $constCacheArray = [];
/**
* Construct an Enum instance.
*
* @param mixed $enumValue
* @return void
*
* @throws \BenSampo\Enum\Exceptions\InvalidEnumMemberException
*/
public function __construct($enumValue)
{
if (! static::hasValue($enumValue)) {
throw new InvalidEnumMemberException($enumValue, $this);
}
$this->value = $enumValue;
$this->key = static::getKey($enumValue);
$this->description = static::getDescription($enumValue);
}
/**
* Make a new instance from an enum value.
*
* @param mixed $enumValue
* @return static
*/
public static function fromValue($enumValue): self
{
if ($enumValue instanceof static) {
return $enumValue;
}
return new static($enumValue);
}
/**
* Alias for fromValue();.
*
* @param mixed $enumValue
* @return static
*
* @deprecated in favour of fromValue(), might be removed in a major version
*/
public static function getInstance($enumValue): self
{
return static::fromValue($enumValue);
}
/**
* Make an enum instance from a given key.
*
* @param string $key
* @return static
*
* @throws \BenSampo\Enum\Exceptions\InvalidEnumKeyException
*/
public static function fromKey(string $key): self
{
if (static::hasKey($key)) {
$enumValue = static::getValue($key);
return new static($enumValue);
}
throw new InvalidEnumKeyException($key, static::class);
}
/**
* Attempt to instantiate an enum by calling the enum key as a static method.
*
* This function defers to the macroable __callStatic function if a macro is found using the static method called.
*
* @param string $method
* @param mixed $parameters
* @return mixed
*/
public static function __callStatic($method, $parameters)
{
if (static::hasMacro($method)) {
return static::macroCallStatic($method, $parameters);
}
return static::fromKey($method);
}
/**
* Delegate magic method calls to macro's or the static call.
*
* While it is not typical to use the magic instantiation dynamically, it may happen
* incidentally when calling the instantiation in an instance method of itself.
* Even when using the `static::KEY()` syntax, PHP still interprets this is a call to
* an instance method when it happens inside of an instance method of the same class.
*
* @param string $method
* @param mixed $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
if (static::hasMacro($method)) {
return $this->macroCall($method, $parameters);
}
return self::__callStatic($method, $parameters);
}
/**
* Checks if this instance is equal to the given enum instance or value.
*
* @param static|mixed $enumValue
* @return bool
*/
public function is($enumValue): bool
{
if ($enumValue instanceof static) {
return $this->value === $enumValue->value;
}
return $this->value === $enumValue;
}
/**
* Checks if this instance is not equal to the given enum instance or value.
*
* @param static|mixed $enumValue
* @return bool
*/
public function isNot($enumValue): bool
{
return ! $this->is($enumValue);
}
/**
* Checks if a matching enum instance or value is in the given array.
*
* @param iterable $values
* @return bool
*/
public function in(iterable $values): bool
{
foreach ($values as $value) {
if ($this->is($value)) {
return true;
}
}
return false;
}
/**
* Checks if a matching enum instance or value is not in the given array.
*
* @param iterable $values
* @return bool
*/
public function notIn(iterable $values): bool
{
foreach ($values as $value) {
if ($this->is($value)) {
return false;
}
}
return true;
}
/**
* Return instances of all the contained values.
*
* @return static[]
*/
public static function getInstances(): array
{
return array_map(
function ($constantValue) {
return new static($constantValue);
},
static::getConstants()
);
}
/**
* Attempt to instantiate a new Enum using the given key or value.
*
* @param mixed $enumKeyOrValue
* @return static|null
*/
public static function coerce($enumKeyOrValue): ?Enum
{
if ($enumKeyOrValue === null) {
return null;
}
if ($enumKeyOrValue instanceof static) {
return $enumKeyOrValue;
}
if (static::hasValue($enumKeyOrValue)) {
return static::fromValue($enumKeyOrValue);
}
if (is_string($enumKeyOrValue) && static::hasKey($enumKeyOrValue)) {
$enumValue = static::getValue($enumKeyOrValue);
return new static($enumValue);
}
return null;
}
/**
* Get all of the constants defined on the class.
*
* @return array
*/
protected static function getConstants(): array
{
$calledClass = get_called_class();
if (! array_key_exists($calledClass, static::$constCacheArray)) {
$reflect = new ReflectionClass($calledClass);
static::$constCacheArray[$calledClass] = $reflect->getConstants();
}
return static::$constCacheArray[$calledClass];
}
/**
* Get all or a custom set of the enum keys.
*
* @param mixed $values
*
* @return array
*/
public static function getKeys($values = null): array
{
if ($values === null) {
return array_keys(static::getConstants());
}
return collect(is_array($values) ? $values : func_get_args())
->map(function ($value) {
return static::getKey($value);
})
->toArray();
}
/**
* Get all or a custom set of the enum values.
*
* @param string|string[]|null $keys
*
* @return array
*/
public static function getValues($keys = null): array
{
if ($keys === null) {
return array_values(static::getConstants());
}
return collect(is_array($keys) ? $keys : func_get_args())
->map(function ($key) {
return static::getValue($key);
})
->toArray();
}
/**
* Get the key for a single enum value.
*
* @param mixed $value
* @return string
*/
public static function getKey($value): string
{
return array_search($value, static::getConstants(), true);
}
/**
* Get the value for a single enum key.
*
* @param string $key
* @return mixed
*/
public static function getValue(string $key)
{
return static::getConstants()[$key];
}
/**
* Get the description for an enum value.
*
* @param mixed $value
* @return string
*/
public static function getDescription($value): string
{
return
static::getLocalizedDescription($value) ??
static::getFriendlyKeyName(static::getKey($value));
}
/**
* Get the localized description of a value.
*
* This works only if localization is enabled
* for the enum and if the key exists in the lang file.
*
* @param mixed $value
* @return string|null
*/
protected static function getLocalizedDescription($value): ?string
{
if (static::isLocalizable()) {
$localizedStringKey = static::getLocalizationKey() . '.' . $value;
if (Lang::has($localizedStringKey)) {
return __($localizedStringKey);
}
}
return null;
}
/**
* Get a random key from the enum.
*
* @return string
*/
public static function getRandomKey(): string
{
$keys = static::getKeys();
return $keys[array_rand($keys)];
}
/**
* Get a random value from the enum.
*
* @return mixed
*/
public static function getRandomValue()
{
$values = static::getValues();
return $values[array_rand($values)];
}
/**
* Get a random instance of the enum.
*
* @return static
*/
public static function getRandomInstance(): self
{
return new static(static::getRandomValue());
}
/**
* Return the enum as an array.
*
* [string $key => mixed $value]
*
* @return array
*/
public static function asArray()
{
return static::getConstants();
}
/**
* Get the enum as an array formatted for a select.
*
* [mixed $value => string description]
*
* @return array
*/
public static function asSelectArray(): array
{
$array = static::asArray();
$selectArray = [];
foreach ($array as $key => $value) {
$selectArray[$value] = static::getDescription($value);
}
return $selectArray;
}
/**
* @deprecated use self::asSelectArray()
*
* @return array
*/
public static function toSelectArray(): array
{
return self::asSelectArray();
}
/**
* Check that the enum contains a specific key.
*
* @param string $key
* @return bool
*/
public static function hasKey(string $key): bool
{
return in_array($key, static::getKeys(), true);
}
/**
* Check that the enum contains a specific value.
*
* @param mixed $value
* @param bool $strict (Optional, defaults to True)
* @return bool
*/
public static function hasValue($value, bool $strict = true): bool
{
$validValues = static::getValues();
if ($strict) {
return in_array($value, $validValues, true);
}
return in_array((string) $value, array_map('strval', $validValues), true);
}
/**
* Transform the key name into a friendly, formatted version.
*
* @param string $key
* @return string
*/
protected static function getFriendlyKeyName(string $key): string
{
if (ctype_upper(preg_replace('/[^a-zA-Z]/', '', $key))) {
$key = strtolower($key);
}
return ucfirst(str_replace('_', ' ', Str::snake($key)));
}
/**
* Check that the enum implements the LocalizedEnum interface.
*
* @return bool
*/
protected static function isLocalizable(): bool
{
return isset(class_implements(static::class)[LocalizedEnum::class]);
}
/**
* Get the default localization key.
*
* @return string
*/
public static function getLocalizationKey(): string
{
return 'enums.' . static::class;
}
/**
* Cast values loaded from the database before constructing an enum from them.
*
* You may need to overwrite this when using string values that are returned
* from a raw database query or a similar data source.
*
* @param mixed $value A raw value that may have any native type
* @return mixed The value cast into the type this enum expects
*/
public static function parseDatabase($value)
{
return $value;
}
/**
* Transform value from the enum instance before it's persisted to the database.
*
* You may need to overwrite this when using a database that expects a different
* type to that used internally in your enum.
*
* @param mixed $value A raw value that may have any native type
* @return mixed The value cast into the type this database expects
*/
public static function serializeDatabase($value)
{
if ($value instanceof self) {
return $value->value;
}
return $value;
}
/**
* Get the name of the caster class to use when casting from / to this cast target.
*
* @param array $arguments
* @return string
* @return string|\Illuminate\Contracts\Database\Eloquent\CastsAttributes|\Illuminate\Contracts\Database\Eloquent\CastsInboundAttributes
*/
public static function castUsing(array $arguments)
{
return new EnumCast(static::class);
}
/**
* Transform the enum instance when it's converted to an array.
*
* @return string
*/
public function toArray()
{
return $this->value;
}
/**
* Transform the enum when it's passed through json_encode.
*
* @return string
*/
public function jsonSerialize()
{
return $this->toArray();
}
/**
* @return string
*/
public function __toString(): string
{
return (string) $this->value;
}
}