phpnomad / enum-polyfill
1.0.1
2025-01-13 11:51 UTC
Requires
- phpnomad/singleton: ^1.0
Requires (Dev)
- phpnomad/tests: ^0.1.0 || ^0.3.0
This package is auto-updated.
Last update: 2026-04-15 02:23:56 UTC
README
phpnomad/enum-polyfill provides a single Enum trait that gives any class with constants the method surface of a PHP 8.1 native enum: cases(), from(), tryFrom(), and isValid(). It exists so projects targeting PHP 7.4 or 8.0 can use the same enum patterns that ship natively in 8.1+, with a clear path to swap in real enums later.
Installation
composer require phpnomad/enum-polyfill
Quick Start
use PHPNomad\Enum\Traits\Enum; class Status { use Enum; public const Active = 'active'; public const Pending = 'pending'; public const Inactive = 'inactive'; } Status::cases(); // ['active', 'pending', 'inactive'] Status::isValid('active'); // true Status::tryFrom('banned'); // null Status::from('active'); // 'active'
Overview
cases()and its aliasgetValues()return every constant value on the class as an array.isValid($value)runs a strict comparison against the constant values.from($value)returns the value if valid or throwsUnexpectedValueException.tryFrom($value)returns the value if valid ornull.- Reflection runs once per class. Values are cached on a singleton via
phpnomad/singleton.
One thing to know before you migrate: the trait returns the raw constant value (a string, an int, whatever the constant is), not a typed enum instance. When you later move a class to a native PHP 8.1 enum, call sites that were holding 'active' will need to hold Status::Active instead.
Documentation
Full docs at phpnomad.com.
License
MIT. See LICENSE.txt.