定制 datomatic/laravel-enum-helper 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

datomatic/laravel-enum-helper

Composer 安装命令:

composer require datomatic/laravel-enum-helper

包简介

Simple opinionated framework agnostic PHP 8.1 enum helper for Laravel

README 文档

README

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.

Related Packages

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 Inspection: isPure(), isBacked(), has(), hasName(), hasValue() methods
  • 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.

Annotation command

A convenient command is available to generate DocBlock annotations for enum classes.

php artisan enum:annotate {class?} {--folder=}

# Single enum
php artisan enum:annotate "Enums\FQN\ClassName"
# All enums in a folder
php artisan enum:annotate --folder=Enums/Folder/Path

This command generate the phpDoc annotations for invokable case methods.

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',...

datomatic/laravel-enum-helper 适用场景与选型建议

datomatic/laravel-enum-helper 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 258.78k 次下载、GitHub Stars 达 33, 最近一次更新时间为 2022 年 06 月 18 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 datomatic/laravel-enum-helper 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 datomatic/laravel-enum-helper 我们能提供哪些服务?
定制开发 / 二次开发

基于 datomatic/laravel-enum-helper 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 258.78k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 33
  • 点击次数: 13
  • 依赖项目数: 3
  • 推荐数: 0

GitHub 信息

  • Stars: 33
  • Watchers: 2
  • Forks: 4
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2022-06-18