|
| 1 | +<?php |
| 2 | +namespace LaunchDarkly; |
| 3 | + |
| 4 | +use SensioLabs\Consul\Exception\ClientException; |
| 5 | +use SensioLabs\Consul\ServiceFactory; |
| 6 | + |
| 7 | +class ConsulFeatureRequester extends FeatureRequesterBase |
| 8 | +{ |
| 9 | + /** @var string */ |
| 10 | + protected $_prefix; |
| 11 | + /** @var \SensioLabs\Consul\Services\KV */ |
| 12 | + protected $_kvClient; |
| 13 | + |
| 14 | + public function __construct($baseUri, $sdkKey, $options) |
| 15 | + { |
| 16 | + parent::__construct($baseUri, $sdkKey, $options); |
| 17 | + |
| 18 | + $consulOpts = isset($options['consul_options']) ? $options['consul_options'] : array(); |
| 19 | + if (isset($options['consul_uri'])) { |
| 20 | + $consulOpts['base_uri'] = $options['consul_uri']; |
| 21 | + } |
| 22 | + $sf = new ServiceFactory($consulOpts); |
| 23 | + $this->_kvClient = $sf->get('kv'); |
| 24 | + |
| 25 | + $prefix = isset($options['consul_prefix']) ? $options['consul_prefix'] : 'launchdarkly'; |
| 26 | + $this->_prefix = $prefix . '/'; |
| 27 | + } |
| 28 | + |
| 29 | + protected function readItemString($namespace, $key) |
| 30 | + { |
| 31 | + try { |
| 32 | + $resp = $this->_kvClient->get($this->makeKey($namespace, $key)); |
| 33 | + } catch (ClientException $e) { |
| 34 | + if ($e->getCode() === 404) { |
| 35 | + return null; |
| 36 | + } |
| 37 | + throw $e; |
| 38 | + } |
| 39 | + $results = $resp->json(); |
| 40 | + if (count($results) != 1) { |
| 41 | + return null; |
| 42 | + } |
| 43 | + return base64_decode($results[0]['Value']); |
| 44 | + } |
| 45 | + |
| 46 | + protected function readItemStringList($namespace) |
| 47 | + { |
| 48 | + try { |
| 49 | + $resp = $this->_kvClient->get($this->makeKey($namespace, ''), array('recurse' => true)); |
| 50 | + } catch (ClientException $e) { |
| 51 | + if ($e->getCode() === 404) { |
| 52 | + return array(); |
| 53 | + } |
| 54 | + throw $e; |
| 55 | + } |
| 56 | + $results = $resp->json(); |
| 57 | + $ret = array(); |
| 58 | + foreach ($results as $result) { |
| 59 | + $ret[] = base64_decode($result['Value']); |
| 60 | + } |
| 61 | + return $ret; |
| 62 | + } |
| 63 | + |
| 64 | + private function makeKey($namespace, $key) |
| 65 | + { |
| 66 | + return $this->_prefix . $namespace . '/' . $key; |
| 67 | + } |
| 68 | +} |
0 commit comments