GetterTrait.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 Hyperf\Constants\Exception\ConstantsException;
  13. use Hyperf\Context\ApplicationContext;
  14. use Hyperf\Contract\TranslatorInterface;
  15. use Psr\Container\ContainerExceptionInterface;
  16. use Psr\Container\NotFoundExceptionInterface;
  17. use function array_shift;
  18. use function is_array;
  19. use function sprintf;
  20. use function strtolower;
  21. use function substr;
  22. trait GetterTrait
  23. {
  24. /**
  25. * @throws ConstantsException
  26. * @throws ContainerExceptionInterface
  27. * @throws NotFoundExceptionInterface
  28. */
  29. public static function getValue(string $name, array $arguments): array|string
  30. {
  31. if (! str_starts_with($name, 'get')) {
  32. throw new ConstantsException("The function {$name} is not defined!");
  33. }
  34. if (empty($arguments)) {
  35. throw new ConstantsException('The Code is required');
  36. }
  37. $code = array_shift($arguments);
  38. $name = strtolower(substr($name, 3));
  39. $message = ConstantsCollector::getValue(static::class, $code, $name);
  40. $result = self::translate($message, $arguments);
  41. // If the result of translate doesn't exist, the result is equal with message, so we will skip it.
  42. if ($result && $result !== $message) {
  43. return $result;
  44. }
  45. if (! empty($arguments)) {
  46. return sprintf($message, ...(array) $arguments[0]);
  47. }
  48. return $message;
  49. }
  50. /**
  51. * @throws ContainerExceptionInterface
  52. * @throws NotFoundExceptionInterface
  53. */
  54. protected static function translate(string $key, array $arguments): null|array|string
  55. {
  56. if (! ApplicationContext::hasContainer() || ! ApplicationContext::getContainer()->has(TranslatorInterface::class)) {
  57. return null;
  58. }
  59. $replace = array_shift($arguments) ?? [];
  60. if (! is_array($replace)) {
  61. return null;
  62. }
  63. $translator = ApplicationContext::getContainer()->get(TranslatorInterface::class);
  64. return $translator->trans($key, $replace);
  65. }
  66. }