Skip to content

Commit 8e7484c

Browse files
onairmarcEncoreBot
andauthored
Add Include and Exclude Support to HasEnumValue::options() (#93)
Co-authored-by: EncoreBot <ghbot@encoredigitalgroup.com>
1 parent 78218e9 commit 8e7484c

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

.git-blame-ignore-revs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,4 @@ edb78e6307a371aff090127ce28aae9369605af8
3939
25c8e2da0ba2d49965926137dd8c26aede06ff32
4040
d4b03b64fcfc69e247b12f5f4afa4bd5f90ce5ab
4141
aa3797614d9280deb1b174d4878d484f2695efec
42+
e224e927dabcd3046455985118ed424c43aba054

src/Objects/Support/Traits/HasEnumValue.php

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use BackedEnum;
66
use EncoreDigitalGroup\StdLib\Objects\Support\Types\Str;
77
use LogicException;
8+
use RuntimeException;
89

910
/**
1011
* Trait for PHP Enums that provides additional functionality.
@@ -55,8 +56,16 @@ public static function from(int|string $value): ?static
5556
return null;
5657
}
5758

58-
public static function options(): array
59+
public static function options(array $include = [], array $exclude = []): array
5960
{
61+
if ($include != []) {
62+
return self::optionsIncluding($include);
63+
}
64+
65+
if ($exclude != []) {
66+
return self::optionsExcluding($exclude);
67+
}
68+
6069
$options = [];
6170

6271
foreach (self::cases() as $case) {
@@ -68,7 +77,13 @@ public static function options(): array
6877

6978
public static function name(self $self): string
7079
{
71-
return $self->name;
80+
$name = Str::formattedTitleCase($self->value);
81+
82+
if (is_array($name)) {
83+
throw new RuntimeException("Name was provided as a string but returned as an array.");
84+
}
85+
86+
return $name;
7287
}
7388

7489
private static function enforceEnum(): void
@@ -80,4 +95,30 @@ private static function enforceEnum(): void
8095
));
8196
}
8297
}
98+
99+
private static function optionsIncluding(array $include): array
100+
{
101+
$options = [];
102+
103+
foreach (self::cases() as $case) {
104+
if (in_array($case, $include)) {
105+
$options[$case->value] = self::name($case);
106+
}
107+
}
108+
109+
return $options;
110+
}
111+
112+
private static function optionsExcluding(array $exclude): array
113+
{
114+
$options = [];
115+
116+
foreach (self::cases() as $case) {
117+
if (!in_array($case, $exclude)) {
118+
$options[$case->value] = self::name($case);
119+
}
120+
}
121+
122+
return $options;
123+
}
83124
}

0 commit comments

Comments
 (0)