|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Enqueue\Redis; |
| 4 | + |
| 5 | +use Enqueue\Psr\PsrConnectionFactory; |
| 6 | +use Predis\Client; |
| 7 | + |
| 8 | +class RedisConnectionFactory implements PsrConnectionFactory |
| 9 | +{ |
| 10 | + /** |
| 11 | + * @var array |
| 12 | + */ |
| 13 | + private $config; |
| 14 | + |
| 15 | + /** |
| 16 | + * @var \Redis |
| 17 | + */ |
| 18 | + private $redis; |
| 19 | + |
| 20 | + /** |
| 21 | + * $config = [ |
| 22 | + * 'host' => can be a host, or the path to a unix domain socket |
| 23 | + * 'port' => optional |
| 24 | + * 'timeout' => value in seconds (optional, default is 0.0 meaning unlimited) |
| 25 | + * 'reserved' => should be null if $retry_interval is specified |
| 26 | + * 'retry_interval' => retry interval in milliseconds. |
| 27 | + * 'vendor' => 'The library used internally to interact with Redis server |
| 28 | + * 'persisted' => bool, Whether it use single persisted connection or open a new one for every context |
| 29 | + * 'lazy' => the connection will be performed as later as possible, if the option set to true |
| 30 | + * ]. |
| 31 | + * |
| 32 | + * @param $config |
| 33 | + */ |
| 34 | + public function __construct(array $config) |
| 35 | + { |
| 36 | + $this->config = array_replace([ |
| 37 | + 'host' => null, |
| 38 | + 'port' => null, |
| 39 | + 'timeout' => null, |
| 40 | + 'reserved' => null, |
| 41 | + 'retry_interval' => null, |
| 42 | + 'vendor' => 'phpredis', |
| 43 | + 'persisted' => false, |
| 44 | + 'lazy' => true, |
| 45 | + ], $config); |
| 46 | + |
| 47 | + $supportedVendors = ['predis', 'phpredis']; |
| 48 | + if (false == in_array($this->config['vendor'], $supportedVendors)) { |
| 49 | + throw new \LogicException(sprintf( |
| 50 | + 'Unsupported redis vendor given. It must be either "%s". Got "%s"', |
| 51 | + implode('", "', $supportedVendors), |
| 52 | + $this->config['vendor'] |
| 53 | + )); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * {@inheritdoc} |
| 59 | + * |
| 60 | + * @return RedisContext |
| 61 | + */ |
| 62 | + public function createContext() |
| 63 | + { |
| 64 | + if ($this->config['lazy']) { |
| 65 | + return new RedisContext(function () { |
| 66 | + $redis = $this->createRedis(); |
| 67 | + $redis->connect(); |
| 68 | + |
| 69 | + return $redis; |
| 70 | + }); |
| 71 | + } |
| 72 | + |
| 73 | + return new RedisContext($this->createRedis()); |
| 74 | + } |
| 75 | + |
| 76 | + /** |
| 77 | + * @return Redis |
| 78 | + */ |
| 79 | + private function createRedis() |
| 80 | + { |
| 81 | + if ('phpredis' == $this->config['vendor'] && false == $this->redis) { |
| 82 | + $this->redis = new PhpRedis(new \Redis(), $this->config); |
| 83 | + } |
| 84 | + |
| 85 | + if ('predis' == $this->config['vendor'] && false == $this->redis) { |
| 86 | + $this->redis = new PRedis(new Client($this->config, ['exceptions' => true])); |
| 87 | + } |
| 88 | + |
| 89 | + return $this->redis; |
| 90 | + } |
| 91 | +} |
0 commit comments