Simple opinionated PHP 8.1 enum helper for Laravel

Overview

Enum Helper-DarkEnum Helper-Light

Laravel Enum Helper

Latest Version on Packagist Pest Tests number GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

This is an extension of the datomatic/enum-helper package based on Laravel Framework. The package consists on a LaravelEnumHelper trait that extends EnumInvokable, EnumFroms, EnumNames, EnumValues, EnumEquality, EnumDescription and add dynamic methods to return a translation or "property" method and relative helper methods.

You can think about it as an EnumDescription trait but completely dynamic.

So you can define a custom method() and have these functions available: [method]s(), [method]sByName(), [method]sByValue(). For example with color() you obtain colors(), colorsByName(), colorsByValue() methods.

The cool thing is you can also avoid writing the method and write only the translations. For example, you can define the property excerpt by writing only the translations on enums.php (see below for explanation) and obtain excerpt(), excerpts(), excerptsByName(), excerptsByValue() methods.

The package use the Laravel Pluralizer component to get the singular method to call or to translate.

If you are using Laravel Nova you can see the Laravel Nova Enum Field

The enum-helper base package summary

You should see the datomatic/enum-helper details on his repository, this is a summary:

  • Invokable cases: get the value of enum "invoking" it statically
  • Construct enum by name or value: from(), tryFrom(), fromName(), tryFromName() for all enums
  • Enums Equality: is(), isNot(), in(), notIn() methods
  • Names: methods to have a list of case names (names(), namesByValue())
  • Values: methods to have a list of case values (values(), valuesByName())
  • Unique ID: get an unique identifier from instance or instance from identifier (uniqueId(), fromUniqueId())
  • Descriptions & Translations: add description to enum with optional translation (description(),descriptions(),descriptionsByName(),descriptionsByValue())

Installation

Laravel 8 or above and PHP 8.1+ are required.

composer require datomatic/laravel-enum-helper

Usage

You can use this functionality simply using the LaravelEnumHelper trait.

use Datomatic\LaravelEnumHelper\LaravelEnumHelper;

// Pure enum 
enum Status
{
    use LaravelEnumHelper;

    case PENDING;
    case ACCEPTED;
    case DISCARDED;
    case NO_RESPONSE;

    public function color(): string
    {
        return match ($this) {
            self::PENDING => '#000000',
            self::ACCEPTED => '#0000FF',
            self::DISCARDED => '#FF0000',
            self::NO_RESPONSE => '#FFFFFF',
        };
    }
}

// BackedEnum
enum StatusString
{   
    use LaravelEnumHelper;

    case PENDING = 'P';
    case ACCEPTED = 'A';
    case DISCARDED = 'D';
    case NO_RESPONSE = 'N';
    
    // or public function color(?string $lang = null): string
    public function color(): string
    {
        ...
    }

After that you can define a custom "property" method like color() or color(?string $lang = null) or define the translations instead.

Translations

Using this trait there is 2 way to manage translation strings.

Using Short Keys

Language strings may be stored in enums.php files within the lang directory. Within this directory, there may be subdirectories for each language supported by the application.

/lang
    /en
        enums.php
    /it
        enums.php

All language files return an array of keyed strings. The array has 3 levels:

  • first level key: the complete class name of the enum
  • second level key: the name of the property to translate
  • third level key: the name/value of the enum case.

The default property is description so if you use only that property you can use just a 2 level array.

// /lang/it/enums.php

return [
    // If you need to translate just the description property
    Status::class => [
        Status::PENDING() => 'In attesa', // using invokable trait functionality
        'ACCEPTED' => 'Accettato', // using the name of pure enum case
        'DISCARDED' => 'Rifiutato',
        'NO_RESPONSE' => 'Nessuna Risposta',
    ],
     // If you need to translate multiple properties (e.g. description, excerpt)
    StatusString::class => [
        'description' => [ // using invokable trait functionality
            StatusString::PENDING() => 'In attesa',
            StatusString::ACCEPTED() => 'Accettato',
            ...
        ],
        'excerpt' => [ // using the value of BackedEnum case
            "P" => 'In attesa',
            "A" => 'Accettato',
    ...

Using Translation Strings As Keys

Language strings are stored as JSON files in the lang directory (e.g. lang/it.json). In this example the description property is translated:

{
  "enums.Namespace\\StatusString.description.P": "In attesa",
  "...":"..."
}

But if you want to use this way, you can simply define the method on Enum class like this description method.

public function description(?string $lang = null): string
{
    return match ($this) {
        self::PENDING => __('Await decision', $lang),
        self::ACCEPTED => __('Recognized valid', $lang),
        self::DISCARDED => __('No longer useful', $lang),
        self::NO_RESPONSE => __('No response', $lang),
    };

[property]() method

This dynamic method try to resolve property() method on the enum.
If the method not exist try to translate the instance value with the framework translation function __("enums.Namespace\EnumClass.property.CASE_NAME").
Because the default property is description, if there isn't a translation to that property there is a fallback that takes the case name humanized. With the other properties, if the translation does not exist, the package throws a TranslationMissing exception.

static [property]s() method

This dynamic method gets a list of case property() returns of the enum. The name of the method is the plural of the property so if you are using property it will be properties().

StatusString::descriptions(); // ['Await decision','Recognized valid','No longer useful','No response']
StatusString::colors(); // ['#000000','#0000FF','#FF0000','#FFFFFF']
// Subset
StatusString::descriptions([StatusString::ACCEPTED, StatusString::NO_RESPONSE]); // ['Recognized valid','No response']
StatusString::colors([StatusString::ACCEPTED, StatusString::NO_RESPONSE]); // ['#0000FF','#FFFFFF']
// Forcing language
Status::descriptions(null, 'it'); // 🇮🇹 ['In attesa','Accettato','Rifiutato','Nessuna Risposta']
StatusString::colors(null, 'it'); // ['#000000','#0000FF','#FF0000','#FFFFFF']
// Subset and language 
Status::descriptions([Status::NO_RESPONSE, Status::DISCARDED], 'it'); // 🇮🇹 ['Nessuna Risposta', 'Rifiutato']
StatusString::colors([StatusString::ACCEPTED, StatusString::NO_RESPONSE], 'it'); // ['#0000FF','#FFFFFF']

static [property]sByName() method

This dynamic method returns an associative array of [case name => property() result]. The name of the method is the plural of the property so if you are using property it will be propertiesByName().

StatusString::descriptionsByName(); // ['PENDING' => 'Await decision', 'ACCEPTED' => 'Recognized valid',...
StatusString::colorsByName(); // ['PENDING' => '#000000','ACCEPTED' => '#0000FF',...
Status::descriptionsByName(); // ['PENDING' => 'Await decision', 'ACCEPTED' => 'Recognized valid',...
// Subset
StatusString::descriptionsByName([StatusString::DISCARDED, StatusString::ACCEPTED]); // ['DISCARDED' => 'No longer useful', 'ACCEPTED' => 'Recognized valid']
Status::descriptionsByName([[Status::PENDING, Status::DISCARDED]); // ['PENDING' => 'Await decision', 'DISCARDED' => 'No longer useful']
// Forcing language
StatusString::descriptionsByName(null, 'it'); // 🇮🇹 ['P' => 'In attesa','A' => 'Accettato',...
// Subset and language 
Status::descriptionsByName([Status::DISCARDED, Status::NO_RESPONSE], 'it'); // 🇮🇹 ['DISCARDED' => 'Rifiutato','NO_RESPONSE' => 'Nessuna Risposta',...

static [property]sByValue() method

This dynamic method returns an associative array of [case value => property() result] on BackedEnum, [case name => property() result] otherwise. The name of the method is the plural of the property so if you are using property it will be propertiesByValue().

Status::descriptionsByValue(); // ['PENDING' => 'Await decision', 'ACCEPTED' => 'Recognized valid',...
StatusString::descriptionsByValue(); // ['P' => 'Await decision', 'A' => 'Recognized valid',...
StatusString::colorsByValue(); // ['P' => '#000000','A' => '#0000FF',...
// Subset
Status::descriptionsByValue([Status::PENDING, Status::DISCARDED]); // ['PENDING' => 'Await decision', 'DISCARDED' => 'No longer useful']
StatusString::descriptionsByValue([StatusString::DISCARDED, StatusString::ACCEPTED]); // ['D' => 'No longer useful', 'A' => 'Recognized valid']
StatusString::colorsByValue([[Status::PENDING, Status::DISCARDED]); // ['P' => '#000000', 'D' => '#FF0000']
// Forcing language
StatusString::descriptionsByValue(null, 'it'); // 🇮🇹 ['P' => 'In attesa','A' => 'Accettato',...
// Subset and language 
Status::descriptionsByValue([StatusString::DISCARDED, StatusString::NO_RESPONSE], 'it'); // 🇮🇹 ['DISCARDED' => 'Rifiutato','NO_RESPONSE' => 'Nessuna Risposta',...

Laravel Nova Enum Field

If you are using Laravel Nova Administrator Panel you can use a package to support the enum-helper or/and laravel-enum-helper.
This package adds the PHP 8.1 enum, EnumDescription and LaravelEnumHelper traits support to Nova, with a Nova Select and Nova Boolean filters ready out of the box.

Package: datomatic/nova-enum-field

You might also like...
Plivo PHP Helper Library

plivo-php The Plivo PHP SDK makes it simpler to integrate communications into your PHP applications using the Plivo REST API. Using the SDK, you will

A PHP 7 value objects helper library.

valueobjects Requirements Requires PHP = 7.1 Installation Through Composer, obviously: composer require funeralzone/valueobjects Extensions This lib

A lightweight mulit-process helper base on PHP.
A lightweight mulit-process helper base on PHP.

workbunny/process 🐇 A lightweight multi-process helper base on PHP. 🐇 简介 这是一个基于ext-pcntl和ext-posix拓展的PHP多进程助手,用于更方便的调用使用。 快速开始 composer require work

:passport_control: Helper for Google's new noCAPTCHA (reCAPTCHA v2 & v3)
:passport_control: Helper for Google's new noCAPTCHA (reCAPTCHA v2 & v3)

noCAPTCHA (new reCAPTCHA) By ARCANEDEV© What is reCAPTCHA? reCAPTCHA is a free service that protects your site from spam and abuse. It uses advanced r

Helper to automatically load various Kirby extensions in a plugin

Autoloader for Kirby Helper to automatically load various Kirby extensions in a plugin Commerical Usage This package is free but if you use it in a co

MODX Helper for Tailwind

TailwindHelper MODX Helper for Tailwind Features This MODX Extra adds a Tailwind helper to the MODX installation: Write a safelist.json on base on chu

🪃 Zero-dependency global `kirbylog()` helper for any content

Kirbylog The most simple, Kirby-esque way to log content to file. Most of the time, I just want to log some string or array to a file. That's what thi

Traits used primarily in the v6 package but also available as a helper package for applications

Phalcon Traits This package contains traits with methods that are used for Phalcon v6 onward. It can also be useful to others that want short snippets

Immutable value object for IPv4 and IPv6 addresses, including helper methods and Doctrine support.

IP is an immutable value object for (both version 4 and 6) IP addresses. Several helper methods are provided for ranges, broadcast and network address

Comments
  • Any chance it is compatible with larastan?

    Any chance it is compatible with larastan?

    Hi, first of all great package I was watching it and it is quite useful.

    As soon as I installed and implemented it I realized that larastan does not detect that the magic methods return the correct data and gives an error of: Call to an undefined static method App\Enums\ActivityLogType::NEW_COMMENT() In my case my Trait is this

    <?php
    
    namespace App\Enums;
    
    use Datomatic\LaravelEnumHelper\LaravelEnumHelper;
    
    enum ActivityLogType
    {
        use LaravelEnumHelper;
    
        case NEW_COMMENT;
    }
    

    I know that this error is more on larastan's side than on the package side, but I would like to ask if it is possible to solve it from the package side.

    opened by mreduar 4
Releases(v1.0.0)
  • v1.0.0(Sep 9, 2022)

  • v0.7.0(Jul 2, 2022)

    After migrating several projects with my fellow @RobertoNegro and listening to different opinions we have decided to simplify the package. From now on, I will consider a pure enum as a StringBackedEnum with names as values, so all ***AsSelect() methods will be replaced by ***ByValue() methods.

    • added definition of description(), descriptions(), descriptionsByName(), descriptionsByValue() to improve code completion and static analysis
    • removed all methods `***AsSelect()
    • removed NotBackedEnum exception
    • added support on ***ByValue() methods also for pure enum using name instead value
    • merged version number with datomatic/enum-helper
    Source code(tar.gz)
    Source code(zip)
  • v0.4.5(Jul 1, 2022)

  • v0.4.4(Jun 30, 2022)

  • v0.4.3(Jun 30, 2022)

  • v0.4.2(Jun 27, 2022)

  • v0.4.1(Jun 27, 2022)

  • v0.4.0(Jun 25, 2022)

    • changed the translation key from name to name/value for using the more comfortable invokable functionality on enums.php
    • added a translation fallback for description property translations

    Example of new translation file

    // /lang/it/enums.php
    
    return [
        // If you need to translate just the description property
        Status::class => [
            Status::PENDING() => 'In attesa', // using invokable trait functionality
            'ACCEPTED' => 'Accettato', // using the name of pure enum case
            'DISCARDED' => 'Rifiutato',
            'NO_RESPONSE' => 'Nessuna Risposta',
        ],
         // If you need to translate multiple properties (e.g. description, excerpt)
        StatusString::class => [
            'description' => [ // using invokable trait functionality
                StatusString::PENDING() => 'In attesa',
                StatusString::ACCEPTED() => 'Accettato',
                ...
            ],
            'excerpt' => [ // using the value of BackedEnum case
                "P" => 'In attesa',
                "A" => 'Accettato',
        ...
    
    Source code(tar.gz)
    Source code(zip)
  • v0.3.0(Jun 21, 2022)

  • v0.2.1(Jun 20, 2022)

  • v0.2.0(Jun 18, 2022)

Owner
Datomatic
Datomatic
An opinionated extension package for Laravel Orchid to extend its table handling capabilities, and some further useful helper methods.

OrchidTables An opinionated extension package for Laravel Orchid to extend its table handling capabilities, and some further useful helper methods. In

null 25 Dec 22, 2022
Simplified and enhanced version of php built-in enum.

PHP Enum enhanced Finally, in php81 has been added support for Enums. But as enums are new in php, we do not have some helpers to work with that easil

Lazizbek Ergashev 40 Nov 20, 2022
This library provides a collection of native enum utilities (traits) which you almost always need in every PHP project.

This library provides a collection of native enum utilities (traits) which you almost always need in every PHP project.

DIVE 20 Nov 11, 2022
Laravel Pint is an opinionated PHP code style fixer for minimalists.

Laravel Pint is an opinionated PHP code style fixer for minimalists. Pint is built on top of PHP-CS-Fixer and makes it simple to ensure that your code style stays clean and consistent.

The Laravel Framework 2.2k Jan 5, 2023
Opinionated version of Wikimedia composer-merge-plugin to work in pair with Bamarni composer-bin-plugin.

Composer Inheritance Plugin Opinionated version of Wikimedia composer-merge-plugin to work in pair with bamarni/composer-bin-plugin. Usage If you are

Théo FIDRY 25 Dec 2, 2022
A simple helper to generate and display pagination navigation links

Intro to CHocoCode Paginator Friendly PHP paginator to paginate everything This package introduces a different way of pagination handling. You can rea

faso-dev 3 Aug 24, 2021
AlphaID Helper - Basic, Simple and Lightweight

AlphaID Helper - Basic, Simple and Lightweight

Hung Nguyen 1 Oct 18, 2021
PHP Japanese string helper functions for converting Japanese strings from full-width to half-width and reverse. Laravel Rule for validation Japanese string only full-width or only half-width.

Japanese String Helpers PHP Japanese string helper functions for converting Japanese strings from full-width to half-width and reverse. Laravel Rule f

Deha 54 Mar 22, 2022
Helper for countries laravel package

Countries helper Helper for countries laravel package Installation You can install the package via composer: composer require eliseekn/countries-helpe

Kouadio Elisée N'GUESSAN 1 Oct 15, 2021
Laravel-hours-helper - Creates a Collection of times with a given interval.

Laravel Hours Helper With laravel-hours-helper you can create a collection of dates and/of times with a specific interval (in minutes) for a specific

Label84 220 Dec 29, 2022