Skip to content

Commit 58eaec4

Browse files
committed
Add validation for enum constants - throw RuntimeException for invalid names
- Constants must follow UPPER_SNAKE_CASE pattern - Only string and int values are allowed - Ensures enum integrity at runtime
1 parent 82129c3 commit 58eaec4

File tree

1 file changed

+26
-6
lines changed

1 file changed

+26
-6
lines changed

src/Common/AbstractEnum.php

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,7 @@ private static function getInstance($value, string $name): self
236236
* Get all constants for this enum class
237237
*
238238
* @return array<string, string|int>
239+
* @throws \RuntimeException If invalid constant found
239240
*/
240241
protected static function getConstants(): array
241242
{
@@ -245,15 +246,34 @@ protected static function getConstants(): array
245246
$reflection = new ReflectionClass($className);
246247
$constants = $reflection->getConstants();
247248

248-
// Filter to only include uppercase snake_case constants
249+
// Validate all constants
249250
$enumConstants = [];
250251
foreach ($constants as $name => $value) {
251-
if (
252-
preg_match('/^[A-Z][A-Z0-9_]*$/', $name)
253-
&& (is_string($value) || is_int($value))
254-
) {
255-
$enumConstants[$name] = $value;
252+
// Check if constant name follows uppercase snake_case pattern
253+
if (!preg_match('/^[A-Z][A-Z0-9_]*$/', $name)) {
254+
throw new \RuntimeException(
255+
sprintf(
256+
'Invalid enum constant name "%s" in %s. Constants must be UPPER_SNAKE_CASE.',
257+
$name,
258+
$className
259+
)
260+
);
256261
}
262+
263+
// Check if value is valid type
264+
if (!is_string($value) && !is_int($value)) {
265+
throw new \RuntimeException(
266+
sprintf(
267+
'Invalid enum value type for constant %s::%s. ' .
268+
'Only string and int values are allowed, %s given.',
269+
$className,
270+
$name,
271+
gettype($value)
272+
)
273+
);
274+
}
275+
276+
$enumConstants[$name] = $value;
257277
}
258278

259279
self::$cache[$className] = $enumConstants;

0 commit comments

Comments
 (0)