From dc60c13b89d9cbc858f3e744c7a09935e5bba294 Mon Sep 17 00:00:00 2001 From: lfyw <1559897062@qq.com> Date: Thu, 10 Mar 2022 17:14:55 +0800 Subject: [PATCH] feat: getDescriptionByValue --- README.md | 13 +++++++++++-- src/Enumable.php | 4 ++++ src/HasEnum.php | 15 ++++++++++++--- 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index f574ccd..7026c03 100644 --- a/README.md +++ b/README.md @@ -75,12 +75,21 @@ enum UserType:string implements Enumable public static function getDescriptions():array { return [ - UserType::Admin => 'super admin', - UserType::Consumer => 'super consumer' + UserType::Admin->name => 'super admin', + UserType::Consumer->name => 'super consumer' ]; } } ``` +#### UserType::getDescriptionByValue($value):string + +根据值获取注释 + +```php +UserType::getDescriptionByValue(UserType::USER->value); +``` + + #### UserType::hasValue($value, bool $strict = false) 检查枚举中是否包含某个值。 diff --git a/src/Enumable.php b/src/Enumable.php index 4a23494..88f0850 100644 --- a/src/Enumable.php +++ b/src/Enumable.php @@ -14,6 +14,10 @@ public static function hasValue($value): bool; public static function hasName(string $key): bool; + public static function getDescriptionByName($name): string; + + public static function getDescriptionByValue($value): string; + public function getDescription(): string; public function getName(); diff --git a/src/HasEnum.php b/src/HasEnum.php index e3fc939..e488e6a 100644 --- a/src/HasEnum.php +++ b/src/HasEnum.php @@ -36,13 +36,22 @@ public static function hasName(string $key): bool return in_array($key, static::getNames(), true); } + public static function getDescriptionByValue($value): string + { + return static::tryFrom($value)?->getDescription(); + } + + public static function getDescriptionByName($name): string + { + return ''; +// return (static::{$name})?->getDescription(); + } + public function getDescription(): string { $descriptions = static::getDescriptions(); - throw_unless(isset($descriptions[$this->name]), new NullDescriptionException('The description is not defined.')); - - return $descriptions[$this->name]; + return $descriptions[$this->name] ?? ''; } public function getName(): string|int