EnumConstantsTrait.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Constants;
  12. use BackedEnum;
  13. use Hyperf\Constants\Exception\ConstantsException;
  14. use Psr\Container\ContainerExceptionInterface;
  15. use Psr\Container\NotFoundExceptionInterface;
  16. use UnitEnum;
  17. use function is_subclass_of;
  18. /**
  19. * @method string getMessage(array $translate = null)
  20. */
  21. trait EnumConstantsTrait
  22. {
  23. use GetterTrait;
  24. /**
  25. * @throws ContainerExceptionInterface
  26. * @throws ConstantsException
  27. * @throws NotFoundExceptionInterface
  28. */
  29. public function __call(string $name, array $arguments): array|string
  30. {
  31. $code = match (true) {
  32. $this instanceof BackedEnum => $this->value,
  33. $this instanceof UnitEnum => $this->name,
  34. default => throw new ConstantsException('This trait must in enum'),
  35. };
  36. return static::getValue($name, [$code, ...$arguments]);
  37. }
  38. /**
  39. * @throws ConstantsException
  40. * @throws ContainerExceptionInterface
  41. * @throws NotFoundExceptionInterface
  42. */
  43. public static function __callStatic(string $name, array $arguments): array|string
  44. {
  45. if (! is_subclass_of(static::class, UnitEnum::class)) {
  46. throw new ConstantsException('This trait must in enum');
  47. }
  48. if (! empty($arguments)) {
  49. if ($arguments[0] instanceof BackedEnum) {
  50. $arguments[0] = $arguments[0]->value;
  51. } elseif ($arguments[0] instanceof UnitEnum) {
  52. $arguments[0] = $arguments[0]->name;
  53. }
  54. }
  55. return static::getValue($name, $arguments);
  56. }
  57. }