dilovanmatini / laravel-enumable
Laravel Enumable 特性提供了一组实用方法来增强 PHP 枚举。它包括操作枚举案例、检索标签以及将枚举转换为各种格式的方法。
v1.0.2
2024-08-10 23:10 UTC
Requires
- php: ^8.1
- spatie/laravel-package-tools: ^1.16.1
Requires (Dev)
- larastan/larastan: ^2.7
- mockery/mockery: ^1.6.7
- orchestra/testbench: ^7.0|^8.17|^9.0
- pestphp/pest: ^2.28
- spatie/pest-plugin-snapshots: ^2.1
README
概述
Laravel Enumable
特性提供了一组实用方法来增强 Laravel 中的 PHP 枚举。它包括操作枚举案例、检索标签以及将枚举转换为各种格式的方法。
安装
要安装 Laravel Enumable
特性,通过 Composer 将其添加到您的项目中
composer require dilovanmatini/laravel-enumable
要求
- PHP 8.1 或更高版本
- Laravel 10.0 或更高版本
用法
在您的枚举类中包含 Enumable
特性
use DilovanMatini\Enumable\Traits\Enumable; enum YourEnum: string { use Enumable; case Example = 'example'; // Add your cases here }
方法
类方法
values()
:返回所有枚举值的数组。names()
:返回所有枚举名称的数组。labels()
:将枚举转换为以值为键、标签为值的关联数组。getCase(string $value)
:返回给定值的枚举案例。getName(string $value)
:返回给定值的枚举案例的名称。getLabel(string $value)
:返回给定值的枚举案例的标签。toArray()
:将枚举转换为以值为键、名称为值的关联数组。toCollection()
:将枚举转换为 Laravel 集合。toSelectArray()
:toLabelsArray() 的别名。exists(object|string $value)
:检查给定的值是否存在于枚举中。random()
:返回一个随机枚举案例。default()
:返回默认枚举案例。first()
:返回第一个枚举案例。last()
:返回最后一个枚举案例。count()
:返回枚举案例的数量。only(array $cases)
:返回一个仅包含指定案例的新对象。except(array $cases)
:返回一个除指定案例之外的所有案例的新对象。generate(array $cases)
:生成一个包含给定案例的新对象。
实例(对象)方法
label()
:返回枚举案例的标签。headline()
:返回枚举案例的大标题。str(bool $label = false)
:返回一个新对象,用于应用 Laravel 字符串辅助方法。
示例
// Class methods YourEnum::values(); // ['example'] YourEnum::names(); // ['Example'] YourEnum::labels(); // ['example' => 'Example'] YourEnum::getCase('example'); // YourEnum::Example YourEnum::getName('example'); // 'Example' YourEnum::getLabel('example'); // 'Example' YourEnum::toArray(); // ['example' => 'Example'] YourEnum::toCollection(); // Collection {#1 ▼ #items: App\Enums\YourEnum [▼ "name" => "Example", "value" => "example", ] } YourEnum::toSelectArray(); // ['example' => 'Example'] YourEnum::exists('example'); // true YourEnum::random(); // YourEnum::Example YourEnum::default(); // YourEnum::Example YourEnum::first(); // YourEnum::Example YourEnum::last(); // YourEnum::Example YourEnum::count(); // 1 YourEnum::only(['Example']); // YourEnum::Example YourEnum::except(['Example']); // YourEnum::Example YourEnum::generate(['Example']); // YourEnum::Example // Instance methods YourEnum::Example->label(); // 'Example' YourEnum::Example->headline(); // 'Example' YourEnum::Example->str()->camel(); // 'example' YourEnum::Example->str()->plural(); // 'Examples'
自定义标签
覆盖您的枚举类中的 setLabels
方法以提供自定义标签
public static function setLabels(): array { return [ self::Example->value => 'Example Custom Label', ]; }
许可证
此软件包是开源软件,根据 MIT 许可证 许可。