A collection of useful traits for working with PHP 8.1 Enums

Related tags

Laravel EnumHelper
Overview

A library of helper traits for working with PHP 8.1 enums

Build Status Total Downloads Latest Stable Version License

This package provides a series of traits that allows you to:

  • RestorableFromName Trait

    Create/restore a PHP 8.1 enum from a name string.

  • EnumValidatableCase

    Validate an enum name from a name string.

Installation

You can install the package via composer:

composer require markbaker/enumhelper

Usage

RestorableFromName Trait

In PHP 8.1, it is possible to create a backed enum from a value using the enum's from() or tryFrom() methods.

enum Suit: string
{
    case Hearts = 'H';
    case Diamonds = 'D';
    case Clubs = 'C';
    case Spades = 'S';
}

$suit = Suit::Diamonds;

$value = $suit->value;      // Returns 'D' 

$newSuit = Suit::from($value);

The EnumHelper\EnumRestorableFromName trait provided in this library adds a fromName() method to any enum where you want to create an enum from its name.

enum Suit: string
{
    use EnumHelper\EnumRestorableFromName;

    case Hearts = 'H';
    case Diamonds = 'D';
    case Clubs = 'C';
    case Spades = 'S';
}

$suit = Suit::Diamonds;

$suitName = $suit->name;      // Returns 'Diamonds' 

$newSuit = Suit::fromName($suitName);

An invalid name will throw an exception. Note that names are case-sensitive.

This could be useful if you wanted to store the name in a database for readability (particularly appropriate for unbacked enums); then recreate the enum in the model when you load the database record.

This works with both backed and unbacked enums.

EnumValidatableCase Trait

Useful to validate if a name has been defined in the case set for an enum:

enum Suit: string
{
    use EnumHelper\EnumValidatableCase;

    case Hearts = 'H';
    case Diamonds = 'D';
    case Clubs = 'C';
    case Spades = 'S';
}

$suit = Suit::Diamonds;

$validCaseName = Suit::Hearts;
$isCaseNameValid = Suit::isValidCase($validCaseName);      // Returns boolean true

$invalidCaseName = 'HeArTs';
$isCaseNameValid = Suit::isValidCase($invalidCaseName);    // Returns boolean false

Note that names are case-sensitive.

This works with both backed and unbacked enums.

Changelog

Please see the CHANGELOG for more information on what has changed recently.

License

This librar is released under the MIT License (MIT). Please see License File for more information.

You might also like...
Collection of agnostic PHP Functions and helpers with zero dependencies to use as foundation in packages and other project

Collection of agnostic PHP Functions and helpers This package provides a lot of very usefull agnostic helpers to use as foundation in packages and oth

Collection of the Laravel/Eloquent Model classes that allows you to get data directly from a Magento 2 database.

Laragento LAravel MAgento Micro services Magento 2 has legacy code based on abandoned Zend Framework 1 with really ugly ORM on top of outdated Zend_DB

A collection of helper functions that I use across my projects.

A collection of helper functions that I use across my projects. This package includes some of the helper functions that I tend to use in all of my pro

A collection of generators for Lumen and Laravel 5.

Lumen generators A collection of generators for Lumen and Laravel 5. Contents Why ? Installation Quick Usage Detailed Usage Model Generator Migration

Base library for repeated layout fields, content builders and other collection components

laravel-flexible-content This package's only purpose is to build custom repeated layout components, such as Laravel Nova's Flexible Content field or y

A collection of extensions for Laravel development in Visual Studio Code

Laravel Extension Pack for Visual Studio Code Includes the basic extensions to get started with Laravel development in Visual Studio Code. Laravel Ext

A package to filter laravel model based on query params or retrieved model collection

Laravel Filterable A package to filter laravel model based on query params or retrived model collection. Installation Require/Install the package usin

Collection of classes you can use to standardize data formats in your Laravel application.
Collection of classes you can use to standardize data formats in your Laravel application.

Laravel Formatters This package is a collection of classes you can use to standardize data formats in your Laravel application. It uses the Service Co

A collection of classes to be extended/used in laravel apps for quick development

laraquick A collection of classes to be extended/used in laravel applications for quick development. Introduction The library contains traits with wel

Releases(1.0.2)
  • 1.0.2(Jan 20, 2022)

    • Added CasesIndexedByName trait, providing a casesIndexedByName() method to return an associative array of cases with the case name as the index, rather than an enumerated array that is returned by cases().
    Source code(tar.gz)
    Source code(zip)
  • 1.0.1(Dec 8, 2021)

    1.0.1 - 2021-12-08

    • Added EnumValidatableCase trait, providing an isValidCase() method to validate a string value against the set of case names defined for an enum.
    Source code(tar.gz)
    Source code(zip)
  • 1.0.0(Dec 7, 2021)

Owner
Mark Baker
Mark Baker
A collection of common algorithms implemented in PHP. The collection is based on "Cracking the Coding Interview" by Gayle Laakmann McDowell

PHPAlgorithms A collection of common algorithms implemented in PHP. The collection is based on "Cracking the Coding Interview" by Gayle Laakmann McDow

Doğan Can Uçar 921 Dec 18, 2022
An opinionated support package for Laravel, that provides flexible and reusable helper methods and traits for commonly used functionality.

Support An opinionated support package for Laravel, that provides flexible and reusable helper methods and traits for commonly used functionality. Ins

Ian Olson 3 Apr 14, 2021
Package with small support traits and classes for the Laravel Eloquent models

Contains a set of traits for the eloquent model. In future can contain more set of classes/traits for the eloquent database.

Martin Kluska 3 Feb 10, 2022
Useful blade components and functionality for most Laravel projects.

laravel-base Note: Package is still in early stages of development, so functionality is subject to change. LaravelBase is a package I've created to pr

Randall Wilk 3 Jan 16, 2022
Extend Laravel PHP framework to make working with Aiven databases simpler

Aiven Commands for Laravel ✨ Add some Aiven magic to your Laravel project ✨ This Laravel package provides some aiven commands for artisan to help with

Aiven 8 Aug 19, 2022
Watch your Laravel app for unwanted changes when working with third-party packages.

Project Secure This package installs a Composer plugin that reports unwanted changes to your Laravel project code after installing or updating a third

The Laravel Hacker 3 Nov 3, 2021
Helper class for working with Laravel Mix in WordPress themes and plugins.

Hybrid\Mix Hybrid Mix is a class for working with Lavarel Mix. It adds helper methods for quickly grabbing asset files cached in the mix-manifest.json

Theme Hybrid 9 Jun 2, 2022
Laravel-FCM is an easy to use package working with both Laravel and Lumen for sending push notification with Firebase Cloud Messaging (FCM).

Laravel-FCM Introduction Laravel-FCM is an easy to use package working with both Laravel and Lumen for sending push notification with Firebase Cloud M

Rahul Thapa 2 Oct 16, 2022
Makes working with DateTime fields in Laravel's Nova easier

This package adds a DateTime field with support for a global DateTime format, syntactic sugar for formatting individual DateTime fields and powerful d

wdelfuego 6 Aug 4, 2022
PHP components - collection of cross-project PHP classes

PHP components Collection of cross-project PHP classes. Install: $ composer require ansas/php-component Ansas\Component\Convert\ConvertPrice Convert "

null 1 Jan 5, 2022