Script.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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\Redis\Lua;
  12. use Hyperf\Contract\StdoutLoggerInterface;
  13. use Hyperf\Redis\Exception\RedisNotFoundException;
  14. use Hyperf\Redis\Redis;
  15. use Psr\Container\ContainerInterface;
  16. use Psr\Log\LoggerInterface;
  17. abstract class Script implements ScriptInterface
  18. {
  19. /**
  20. * PHPRedis client or proxy client.
  21. * @var mixed|\Redis
  22. */
  23. protected mixed $redis;
  24. protected ?string $sha = null;
  25. protected ?LoggerInterface $logger = null;
  26. public function __construct(ContainerInterface $container)
  27. {
  28. if ($container->has(Redis::class)) {
  29. $this->redis = $container->get(Redis::class);
  30. }
  31. if ($container->has(StdoutLoggerInterface::class)) {
  32. $this->logger = $container->get(StdoutLoggerInterface::class);
  33. }
  34. }
  35. public function eval(array $arguments = [], $sha = true): mixed
  36. {
  37. if ($this->redis === null) {
  38. throw new RedisNotFoundException('Redis client is not found.');
  39. }
  40. if ($sha) {
  41. $result = $this->redis->evalSha($this->getSha(), $arguments, $this->getKeyNumber($arguments));
  42. if ($result !== false) {
  43. return $this->format($result);
  44. }
  45. $this->sha = null;
  46. $this->logger && $this->logger->warning(sprintf('NOSCRIPT No matching script[%s]. Use EVAL instead.', static::class));
  47. }
  48. $result = $this->redis->eval($this->getScript(), $arguments, $this->getKeyNumber($arguments));
  49. return $this->format($result);
  50. }
  51. protected function getKeyNumber(array $arguments): int
  52. {
  53. return count($arguments);
  54. }
  55. protected function getSha(): string
  56. {
  57. if (! empty($this->sha)) {
  58. return $this->sha;
  59. }
  60. return $this->sha = $this->redis->script('load', $this->getScript());
  61. }
  62. }