Tinkerwell - The PHP Scratchpad

EnumConcern - Effortless Enumeration Handling in PHP

Published on by

EnumConcern - Effortless Enumeration Handling in PHP image

EnumConcern is a newly introduced PHP package tailored to streamline the usage of PHP's Enum feature by providing a comprehensive suite of methods. Backed by Laravel Collections, EnumConcern aims to offer a seamless and familiar experience.

Key Features of EnumConcern:

  • Versatility: EnumConcern includes a variety of methods that enable easy handling of Enums, such as all, has, caseExists, and more.
  • Conversion Capabilities: The package offers methods to convert Enums to various formats like JSON, array, or key-value collections.
  • Customization: There's flexibility in obtaining subsets of values with the methods only, onlyAsArray, except, exceptAsArray, etc.
  • Utility Functions: Functions like randomValue, randomCase, first, and last provide extra utility.

EnumConcern Usage:

EnumConcern integrates smoothly into existing enums, enabling functions like translation and various checks. Here's an example of how to translate color Enums to Turkish:

namespace App\Enums;
 
use EmreYarligan\EnumConcern\EnumConcern;
 
enum Color: string
{
use EnumConcern;
 
case RED = "Red";
case GREEN = "Green";
case BLUE = "Blue";
 
public function translateToTurkish(): string
{
return match ($this) {
self::RED => 'Kırmızı',
self::GREEN => 'Yeşil',
self::BLUE => 'Mavi',
};
}
 
}
 
Color::all();
// Result: Illuminate\Support\Collection (7) [
// [0] => 'Red',
// [1] => 'Green',
// [2] => 'Blue
// ]
 
Color::all('translateToTurkish');
// Result: Illuminate\Support\Collection (7) [
// [0] => 'Kırmızı',
// [1] => 'Yeşil',
// [2] => 'Mavi
// ]
 
Color::has('Purple');
// false
 
Color::has('Mavi','translateToTurkish');
// true

With functions like Color::all('translateToTurkish'), you can retrieve translated values effortlessly.

EnumConcern Methods

  • all: Get all the values as a Collection. Parameters: method = '' (optional). Return Type: Collection.
  • allAsArray: Get all the values as an array. Parameters: method = '' (optional). Return Type: array.
  • has: Check if a specific value exists. Parameters: value, method = '' (optional). Return Type: bool.
  • caseExists: Check if a specific case (key / name) exists. Parameters: value, method = '' (optional). Return Type: bool.
  • allCasesExists: Check if all the given cases (keys/names) exist. Parameters: cases, method = '' (optional). Return Type: bool.
  • anyCaseExists: Check if any of the given cases (keys/names) exist. Parameters: cases, method = '' (optional). Return Type: bool.
  • caseByValue: Get the case (key/name) for a specific value. Parameters: value, method = '' (optional). Return Type: string.
  • toJson: Convert all the values to a JSON string. Parameters: method = '' (optional), jsonEncodeOption (optional). Return Type: string.
  • toArray: Convert all the values to an array. Parameters: method = '' (optional). Return Type: array.
  • toKeyValueCollection: Convert all the values to a key-value format as a Collection. Parameters: method = '' (optional). Return Type: Collection.
  • toKeyValueArray: Convert all the values to a key-value format as an array. Parameters: method = '' (optional). Return Type: array.
  • randomValue: Get a random value from the collection of values. Parameters: method = '' (optional). Return Type: mixed.
  • randomCase: Get a random case (key/name) from the collection of values. Parameters: None. Return Type: string.
  • casesCollection: Get all the cases (keys/names) of the Enum as a Collection. Parameters: None. Return Type: Collection.
  • casesArray: Get all the cases (keys/names) of the Enum as an array. Parameters: None. Return Type: array.
  • allToArray: Get all the values as an array (Alias for toArray method). Parameters: method = '' (optional). Return Type: array.
  • only: Get a subset of the values as a Collection, only including the specified cases (keys/names). Parameters: cases, method = '' (optional). Return Type: Collection.
  • onlyAsArray: Get a subset of the values as an array, only including the specified cases (keys/names). Parameters: cases, method = '' (optional). Return Type: array.
  • except: Get a subset of the values as a Collection, excluding the specified cases (keys/names). Parameters: cases, method = '' (optional). Return Type: Collection.
  • exceptAsArray: Get a subset of the values as an array, excluding the specified cases (keys/names). Parameters: cases, method = '' (optional). Return Type: array.
  • first: Get the first value in the Enum. Parameters: method = '' (optional). Return Type: mixed.
  • last: Get the last value in the Enum. Parameters: method = '' (optional). Return Type: mixed.

Conclusion:

EnumConcern offers a robust solution for managing Enums in PHP, integrating seamlessly with Laravel Collections and providing a host of useful methods. Whether you need to check, convert, or manipulate Enums, EnumConcern simplifies the process, saving time and effort.

For more detailed examples and comprehensive documentation, you can refer to the official EnumConcern documentation.

Eric L. Barnes photo

Eric is the creator of Laravel News and has been covering Laravel since 2012.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Tinkerwell

Enjoy coding and debugging in an editor designed for fast feedback and quick iterations. It's like a shell for your application – but with multi-line editing, code completion, and more.

Visit Tinkerwell
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
JSON:API Resource in Laravel 12.45 image

JSON:API Resource in Laravel 12.45

Read article
Caching With MongoDB for Faster Laravel Apps image

Caching With MongoDB for Faster Laravel Apps

Read article
Laravel 12.44 Adds HTTP Client afterResponse() Callbacks image

Laravel 12.44 Adds HTTP Client afterResponse() Callbacks

Read article
Handle Nested Data Structures in PHP with the Data Block Package image

Handle Nested Data Structures in PHP with the Data Block Package

Read article
Detect and Clean Up Unchanged Vendor Files with Laravel Vendor Cleanup image

Detect and Clean Up Unchanged Vendor Files with Laravel Vendor Cleanup

Read article
Seamless PropelAuth Integration in Laravel with Earhart image

Seamless PropelAuth Integration in Laravel with Earhart

Read article