Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Enum Helper Laravel Package

oskarstark/enum-helper

Helpers for PHP 8.1+ enums: compare enum cases (equals, notEquals, equalsOneOf) and convert enums to arrays (backed and non-backed). Includes an abstract EnumTestCase to simplify testing enum behavior.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Pros:

    • Lightweight (~100 lines of code) and MIT-licensed, making it ideal for Laravel/PHP projects requiring minimal dependencies.
    • Trait-based design aligns with Laravel’s composable architecture (e.g., use Comparable, use ToArray).
    • PHP 8.1+ enums are a first-class citizen in Laravel 10+, and this package provides standardized utility methods (equals(), toArray(), etc.) that reduce boilerplate.
    • TestCase abstraction (EnumTestCase) simplifies unit testing for enums, which is valuable for Laravel’s test-driven workflows.
    • No framework coupling: Works with any PHP enum, including Laravel’s built-in enums (e.g., Illuminate\Database\Eloquent\Casts\Attribute enums).
  • Cons:

    • Limited scope: Focuses only on comparison and array conversion—does not handle serialization, validation, or database interactions (unlike Spatie/enum or Laravel\Enum).
    • No Laravel-specific integrations (e.g., Eloquent model casting, Blade directives, or API resource transformations).

Integration Feasibility

  • High:

    • Composer install: Zero configuration (composer require oskarstark/enum-helper).
    • Backward compatibility: Supports PHP 8.1+ (Laravel 10+ minimum) and PHP 8.2+ (Laravel 11+).
    • Zero runtime overhead: Traits are only loaded when used (autoloaded via Composer).
    • Static analysis friendly: Type hints and PHPDoc improve IDE support (e.g., equalsOneOf() autocompletion).
  • Potential Conflicts:

    • Enum naming collisions: If your project already uses Comparable or ToArray as trait/class names, rename the imported traits (e.g., use OskarStark\Enum\Trait\EnumComparable).
    • PHPStan/PHPUnit: The package uses #[Test] attributes (PHPUnit 9.5+), which may require minor config updates if your project uses older versions.

Technical Risk

  • Low:

    • Mature: 18 releases since 2023, with CI/CD and PHPStan/PHP-CS-Fixer integration.
    • No breaking changes: API is stable (e.g., equalsOneOf() now accepts arrays instead of ...$items).
    • Isolated: No database or filesystem dependencies; risk is limited to enum logic.
  • Mitigations:

    • Test in isolation: Use the EnumTestCase to validate enum behavior before full integration.
    • Gradual adoption: Start with a single enum (e.g., UserRole) to test traits before rolling out globally.

Key Questions

  1. Does Laravel already solve this?

    • Laravel 10+ enums support basic ->value and tryFrom(), but lack bulk operations (e.g., equalsOneOf()).
    • Tradeoff: This package adds convenience; native enums are sufficient for simple cases.
  2. Performance impact?

    • Negligible: Traits add ~5–10 lines of code per enum; no runtime performance cost beyond native enum checks.
  3. Testing strategy:

    • Extend EnumTestCase for all enums or use it as a template for custom test classes?
    • Example:
      use OskarStark\Enum\Test\EnumTestCase;
      
      class UserRoleTest extends EnumTestCase {
          protected function enumClass(): string { return UserRole::class; }
      }
      
  4. Future-proofing:

    • Will Laravel’s enum support (e.g., #48152) reduce dependency on this package?
    • Decision: Use this package now if you need equalsOneOf()/toArray() today; migrate to native enums later if Laravel adds these features.

Integration Approach

Stack Fit

  • Laravel 10+ (PHP 8.1+):
    • Native enums: Works seamlessly with Laravel’s built-in enums (e.g., class UserStatus extends Enum).
    • Eloquent: Useful for enum casts (e.g., protected $casts = ['status' => UserStatus::class]).
    • APIs: ToArray trait simplifies JSON serialization (e.g., return UserStatus::toArray() in API responses).
  • Legacy PHP 8.0:
    • Not supported (package requires PHP 8.1+).

Migration Path

  1. Assessment Phase:

    • Audit existing enums: Identify candidates for Comparable/ToArray (e.g., UserRole, OrderStatus).
    • Example:
      enum UserRole: string {
          use Comparable, ToArray;
          case ADMIN = 'admin';
          case USER = 'user';
      }
      
  2. Pilot Integration:

    • Add the package to a single module (e.g., auth).
    • Test equalsOneOf() in validation logic:
      if (request()->user()->role->equalsOneOf([UserRole::ADMIN, UserRole::EDITOR])) {
          // Allow action
      }
      
  3. Global Rollout:

    • Use Rector (included in the package) to auto-apply traits to enums via:
      vendor/bin/rector process src --dry-run
      
    • Update tests to extend EnumTestCase:
      class UserRoleTest extends EnumTestCase {
          protected function enumClass(): string { return UserRole::class; }
      }
      
  4. Deprecation Plan:

    • Monitor Laravel’s enum improvements (e.g., #48152).
    • Replace traits with native methods if Laravel adds equalsOneOf()/toArray().

Compatibility

  • Laravel Services:
    • Eloquent: Works with enum casts (e.g., protected $casts = ['status' => OrderStatus::class]).
    • Blade: Use {{ $order->status->value }} or {{ json_encode(OrderStatus::toArray()) }}.
    • API Resources: Leverage ToArray for toArray() methods:
      public function toArray($request) {
          return [
              'status' => $this->resource->status->value,
              'status_options' => OrderStatus::toArray(),
          ];
      }
      
  • Third-Party Packages:
    • No conflicts: The package is enum-agnostic and doesn’t interact with Laravel’s service container.

Sequencing

Phase Task Dependencies
Prep Update composer.json and run composer update. None
Pilot Apply traits to 1–2 enums (e.g., UserRole, OrderStatus). oskarstark/enum-helper
Testing Extend EnumTestCase and run tests. PHPUnit 9.5+
Rector (Optional) Auto-apply traits to all enums using Rector. Rector installed
Documentation Update API docs to reflect enum methods (e.g., equalsOneOf()). None
Monitor Track Laravel’s enum improvements for potential migration. None

Operational Impact

Maintenance

  • Pros:

    • Minimal overhead: Traits require no runtime configuration.
    • Self-documenting: Methods like isNice() improve code readability.
    • Test coverage: EnumTestCase reduces flakiness in enum-related tests.
  • Cons:

    • Trait pollution: Overusing traits may make enums harder to read (mitigate by documenting usage).
    • Dependency: Adding a new package requires version management (though MIT license reduces risk).

Support

  • Debugging:
    • Clear error messages: Methods like equalsOneOf() throw exceptions for invalid inputs.
    • Stack traces: Trait methods include file/line info for debugging.
  • Community:
    • Limited support: No GitHub discussions or Slack community (rely on GitHub issues).
    • Workarounds: Fork the repo if critical fixes are needed (MIT license permits this).

Scaling

  • Performance:
    • No impact: Traits add zero runtime overhead beyond native enum checks.
    • Memory: Minimal (traits are statically analyzed and inlined by PHP).
  • Usage Patterns:
    • Bulk operations: equalsOneOf()/notEqualsOneOf() scale well for validation (e.g., role checks).
    • Serialization: ToArray is efficient for API responses (avoids manual case mappings).

**Failure

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky