kongulov/interact-with-enum

Trait for convenient use of ENUM in PHP

Fund package maintenance!
kongulov

1.0.0 2023-06-28 19:30 UTC

This package is auto-updated.

Last update: 2024-12-07 07:03:24 UTC


README

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"
}