|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Enqueue\Gearman; |
| 4 | + |
| 5 | +use Enqueue\Psr\PsrConnectionFactory; |
| 6 | + |
| 7 | +class GearmanConnectionFactory implements PsrConnectionFactory |
| 8 | +{ |
| 9 | + /** |
| 10 | + * @var array |
| 11 | + */ |
| 12 | + private $config; |
| 13 | + |
| 14 | + /** |
| 15 | + * The config could be an array, string DSN or null. In case of null it will attempt to connect to localhost with default settings. |
| 16 | + * |
| 17 | + * [ |
| 18 | + * 'host' => 'localhost', |
| 19 | + * 'port' => 11300 |
| 20 | + * ] |
| 21 | + * |
| 22 | + * or |
| 23 | + * |
| 24 | + * gearman://host:port |
| 25 | + * |
| 26 | + * @param array|string $config |
| 27 | + */ |
| 28 | + public function __construct($config = 'gearman://') |
| 29 | + { |
| 30 | + if (empty($config) || 'gearman://' === $config) { |
| 31 | + $config = []; |
| 32 | + } elseif (is_string($config)) { |
| 33 | + $config = $this->parseDsn($config); |
| 34 | + } elseif (is_array($config)) { |
| 35 | + } else { |
| 36 | + throw new \LogicException('The config must be either an array of options, a DSN string or null'); |
| 37 | + } |
| 38 | + |
| 39 | + $this->config = array_replace($this->defaultConfig(), $config); |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * {@inheritdoc} |
| 44 | + * |
| 45 | + * @return GearmanContext |
| 46 | + */ |
| 47 | + public function createContext() |
| 48 | + { |
| 49 | + return new GearmanContext($this->config); |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * @param string $dsn |
| 54 | + * |
| 55 | + * @return array |
| 56 | + */ |
| 57 | + private function parseDsn($dsn) |
| 58 | + { |
| 59 | + $dsnConfig = parse_url($dsn); |
| 60 | + if (false === $dsnConfig) { |
| 61 | + throw new \LogicException(sprintf('Failed to parse DSN "%s"', $dsn)); |
| 62 | + } |
| 63 | + |
| 64 | + $dsnConfig = array_replace([ |
| 65 | + 'scheme' => null, |
| 66 | + 'host' => null, |
| 67 | + 'port' => null, |
| 68 | + 'user' => null, |
| 69 | + 'pass' => null, |
| 70 | + 'path' => null, |
| 71 | + 'query' => null, |
| 72 | + ], $dsnConfig); |
| 73 | + |
| 74 | + if ('gearman' !== $dsnConfig['scheme']) { |
| 75 | + throw new \LogicException(sprintf('The given DSN scheme "%s" is not supported. Could be "gearman" only.', $dsnConfig['scheme'])); |
| 76 | + } |
| 77 | + |
| 78 | + return [ |
| 79 | + 'port' => $dsnConfig['port'], |
| 80 | + 'host' => $dsnConfig['host'], |
| 81 | + ]; |
| 82 | + } |
| 83 | + |
| 84 | + /** |
| 85 | + * @return array |
| 86 | + */ |
| 87 | + private function defaultConfig() |
| 88 | + { |
| 89 | + return [ |
| 90 | + 'host' => \GEARMAN_DEFAULT_TCP_HOST, |
| 91 | + 'port' => \GEARMAN_DEFAULT_TCP_PORT, |
| 92 | + ]; |
| 93 | + } |
| 94 | +} |
0 commit comments