|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Hypervel\Redis; |
| 6 | + |
| 7 | +use Closure; |
| 8 | +use FriendsOfHyperf\Redis\Subscriber\Exception\SocketException; |
| 9 | +use FriendsOfHyperf\Redis\Subscriber\Subscriber as RedisSubscriber; |
| 10 | +use Hyperf\Contract\StdoutLoggerInterface; |
| 11 | +use Hypervel\Context\ApplicationContext; |
| 12 | +use Hypervel\Support\Arr; |
| 13 | + |
| 14 | +class Subscriber |
| 15 | +{ |
| 16 | + public function __construct( |
| 17 | + protected array $config, |
| 18 | + protected ?RedisSubscriber $subscriber = null |
| 19 | + ) { |
| 20 | + $this->subscriber = $subscriber ?: $this->createSubscriber($config); |
| 21 | + } |
| 22 | + |
| 23 | + protected function createSubscriber(array $config): RedisSubscriber |
| 24 | + { |
| 25 | + return new RedisSubscriber( |
| 26 | + $config['host'] ?? 'localhost', |
| 27 | + $config['port'] ?? 6379, |
| 28 | + $config['auth'] ?? '', |
| 29 | + $config['timeout'] ?? 5, |
| 30 | + $config['options']['prefix'] ?? '', |
| 31 | + ApplicationContext::getContainer()->get(StdoutLoggerInterface::class), |
| 32 | + ); |
| 33 | + } |
| 34 | + |
| 35 | + /** |
| 36 | + * Subscribe to a set of given channels for messages. |
| 37 | + */ |
| 38 | + public function subscribe(array|string $channels, Closure $callback): void |
| 39 | + { |
| 40 | + $this->subscriber->subscribe(...Arr::wrap($channels)); |
| 41 | + |
| 42 | + while ($data = $this->subscriber->channel()->pop()) { |
| 43 | + $callback($data->payload, $data->channel); |
| 44 | + } |
| 45 | + |
| 46 | + if (! $this->subscriber->closed) { |
| 47 | + throw new SocketException('Redis connection is disconnected abnormally.'); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * Subscribe to a set of given channels with wildcards. |
| 53 | + */ |
| 54 | + public function psubscribe(array|string $channels, Closure $callback): void |
| 55 | + { |
| 56 | + $this->subscriber->psubscribe(...Arr::wrap($channels)); |
| 57 | + |
| 58 | + while ($data = $this->subscriber->channel()->pop()) { |
| 59 | + $callback($data->payload, $data->channel); |
| 60 | + } |
| 61 | + |
| 62 | + if (! $this->subscriber->closed) { |
| 63 | + throw new SocketException('Redis connection is disconnected abnormally.'); |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments