Skip to content

Commit

Permalink
feat: getDescriptionByValue
Browse files Browse the repository at this point in the history
  • Loading branch information
lfyw committed Mar 10, 2022
1 parent b2706cf commit dc60c13
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 5 deletions.
13 changes: 11 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

检查枚举中是否包含某个值。
Expand Down
4 changes: 4 additions & 0 deletions src/Enumable.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
15 changes: 12 additions & 3 deletions src/HasEnum.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit dc60c13

Please sign in to comment.