Skip to content

feat: resolve a BackedEnum case by name (fromName/tryFromName)#1

Merged
k2gl merged 2 commits into
mainfrom
feat/from-name
Jun 5, 2026
Merged

feat: resolve a BackedEnum case by name (fromName/tryFromName)#1
k2gl merged 2 commits into
mainfrom
feat/from-name

Conversation

@k2gl
Copy link
Copy Markdown
Owner

@k2gl k2gl commented Jun 4, 2026

Summary

Native BackedEnum only offers from()/tryFrom(), which resolve a case by its backing value. There is no built-in way to resolve a case by its name (the case identifier), so callers hand-roll a cases() loop whenever they hold a name string from config, serialized data, a CLI argument or a route parameter.

This PR adds the symmetric pair, mirroring the native API:

CardSuit::fromName('SPADES');    // CardSuit::SPADES
CardSuit::tryFromName('SPADES'); // CardSuit::SPADES
CardSuit::tryFromName('joker');  // null
CardSuit::fromName('joker');     // throws \ValueError
  • fromName(string $name): static — throws \ValueError on an unknown name.
  • tryFromName(string $name): ?static — returns null on an unknown name.
  • Name matching is case-sensitive and does not match backing values.

Both are added to ExtendedBackedEnum (trait) and ExtendedBackedEnumInterface. Consumers using the trait get the implementation for free.

Also in this PR

  • README fix: the usage example imported non-existent namespaces (K2gl\Enum\src\…, K2gl\Enum\Types\…); corrected to the real K2gl\Enum\… paths so the snippet actually compiles.
  • PHPStan level 6 → 9, aligning the package with the rest of the collection. No source changes were required to pass.

Tests

New FromNameTest / TryFromNameTest cover valid names, unknown names, case-sensitivity and the "backing value is not a name" case for both string- and int-backed enums. Full gate green: PHPUnit (57 tests), PHPStan level 9, Pint.

@k2gl k2gl force-pushed the feat/from-name branch from ba24cc0 to 64c2d76 Compare June 5, 2026 18:21
@k2gl k2gl merged commit f3baebb into main Jun 5, 2026
8 checks passed
@k2gl k2gl deleted the feat/from-name branch June 5, 2026 18:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant