interact-with-enum icon indicating copy to clipboard operation
interact-with-enum copied to clipboard

Trait for convenient use of ENUM in PHP

Interact With Enum in PHP

Latest Version on Packagist Licence Total Downloads

This package contains the InteractWithEnum.php trait, which you can use to conveniently work with ENUMs.

Requirements

  • php: >=8.1

Installation

Install the package via Composer:

# Install interact-with-enum
composer require kongulov/interact-with-enum

Usage

Imagine you have ENUM StatusEnum.php where we already use the InteractWithEnum trait:

<?php

namespace App\Enums;

use Kongulov\Traits\InteractWithEnum;

enum StatusEnum: string {
    use InteractWithEnum;

    case Pending = 'pending';
    case Active = 'active';
    case Inactive = 'inactive';
}

After using the trait, you can call methods:

  • names()
StatusEnum::names()

Return:

array:3 [
  0 => "Pending"
  1 => "Active"
  2 => "Inactive"
]
  • values()
StatusEnum::values()

Return:

array:3 [
  0 => "pending"
  1 => "active"
  2 => "inactive"
]
  • array()
StatusEnum::array()

Return:

array:3 [
  "pending" => "Pending"
  "active" => "Active"
  "inactive" => "Inactive"
]
  • find($needle)
StatusEnum::find('Active') // Find by name
StatusEnum::find('active') // Find by value

Return:

App\Enums\StatusEnum {
  name: "Active"
  value: "active"
}