ConnectionParameters.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. <?php
  2. /*
  3. * This file is part of the Predis package.
  4. *
  5. * (c) Daniele Alessandri <suppakilla@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Predis;
  11. use Predis\Option\OptionInterface;
  12. /**
  13. * Handles parsing and validation of connection parameters.
  14. *
  15. * @author Daniele Alessandri <suppakilla@gmail.com>
  16. */
  17. class ConnectionParameters implements ConnectionParametersInterface
  18. {
  19. private static $defaultParameters;
  20. private static $validators;
  21. private $parameters;
  22. private $userDefined;
  23. /**
  24. * @param string|array Connection parameters in the form of an URI string or a named array.
  25. */
  26. public function __construct($parameters = array())
  27. {
  28. self::ensureDefaults();
  29. if (!is_array($parameters)) {
  30. $parameters = $this->parseURI($parameters);
  31. }
  32. $this->userDefined = array_keys($parameters);
  33. $this->parameters = $this->filter($parameters) + self::$defaultParameters;
  34. }
  35. /**
  36. * Ensures that the default values and validators are initialized.
  37. */
  38. private static function ensureDefaults()
  39. {
  40. if (!isset(self::$defaultParameters)) {
  41. self::$defaultParameters = array(
  42. 'scheme' => 'tcp',
  43. 'host' => '127.0.0.1',
  44. 'port' => 6379,
  45. 'database' => null,
  46. 'password' => null,
  47. 'connection_async' => false,
  48. 'connection_persistent' => false,
  49. 'connection_timeout' => 5.0,
  50. 'read_write_timeout' => null,
  51. 'alias' => null,
  52. 'weight' => null,
  53. 'path' => null,
  54. 'iterable_multibulk' => false,
  55. 'throw_errors' => true,
  56. );
  57. }
  58. if (!isset(self::$validators)) {
  59. $bool = function($value) { return (bool) $value; };
  60. $float = function($value) { return (float) $value; };
  61. $int = function($value) { return (int) $value; };
  62. self::$validators = array(
  63. 'port' => $int,
  64. 'connection_async' => $bool,
  65. 'connection_persistent' => $bool,
  66. 'connection_timeout' => $float,
  67. 'read_write_timeout' => $float,
  68. 'iterable_multibulk' => $bool,
  69. 'throw_errors' => $bool,
  70. );
  71. }
  72. }
  73. /**
  74. * Defines a default value and a validator for the specified parameter.
  75. *
  76. * @param string $parameter Name of the parameter.
  77. * @param mixed $default Default value or an instance of OptionInterface.
  78. * @param mixed $callable A validator callback.
  79. */
  80. public static function define($parameter, $default, $callable = null)
  81. {
  82. self::ensureDefaults();
  83. self::$defaultParameters[$parameter] = $default;
  84. if ($default instanceof OptionInterface) {
  85. self::$validators[$parameter] = $default;
  86. return;
  87. }
  88. if (!isset($callable)) {
  89. unset(self::$validators[$parameter]);
  90. return;
  91. }
  92. if (!is_callable($callable)) {
  93. throw new \InvalidArgumentException(
  94. "The validator for $parameter must be a callable object"
  95. );
  96. }
  97. self::$validators[$parameter] = $callable;
  98. }
  99. /**
  100. * Undefines the default value and validator for the specified parameter.
  101. *
  102. * @param string $parameter Name of the parameter.
  103. */
  104. public static function undefine($parameter)
  105. {
  106. self::ensureDefaults();
  107. unset(self::$defaultParameters[$parameter], self::$validators[$parameter]);
  108. }
  109. /**
  110. * Parses an URI string and returns an array of connection parameters.
  111. *
  112. * @param string $uri Connection string.
  113. * @return array
  114. */
  115. private function parseURI($uri)
  116. {
  117. if (stripos($uri, 'unix') === 0) {
  118. // Hack to support URIs for UNIX sockets with minimal effort.
  119. $uri = str_ireplace('unix:///', 'unix://localhost/', $uri);
  120. }
  121. if (($parsed = @parse_url($uri)) === false || !isset($parsed['host'])) {
  122. throw new ClientException("Invalid URI: $uri");
  123. }
  124. if (isset($parsed['query'])) {
  125. foreach (explode('&', $parsed['query']) as $kv) {
  126. @list($k, $v) = explode('=', $kv);
  127. $parsed[$k] = $v;
  128. }
  129. unset($parsed['query']);
  130. }
  131. return $parsed;
  132. }
  133. /**
  134. * Validates and converts each value of the connection parameters array.
  135. *
  136. * @param array $parameters Connection parameters.
  137. * @return array
  138. */
  139. private function filter(Array $parameters)
  140. {
  141. if (count($parameters) > 0) {
  142. $validators = array_intersect_key(self::$validators, $parameters);
  143. foreach ($validators as $parameter => $validator) {
  144. $parameters[$parameter] = $validator($parameters[$parameter]);
  145. }
  146. }
  147. return $parameters;
  148. }
  149. /**
  150. * {@inheritdoc}
  151. */
  152. public function __get($parameter)
  153. {
  154. $value = $this->parameters[$parameter];
  155. if ($value instanceof OptionInterface) {
  156. $this->parameters[$parameter] = ($value = $value->getDefault());
  157. }
  158. return $value;
  159. }
  160. /**
  161. * {@inheritdoc}
  162. */
  163. public function __isset($parameter)
  164. {
  165. return isset($this->parameters[$parameter]);
  166. }
  167. /**
  168. * Checks if the specified parameter has been set by the user.
  169. *
  170. * @param string $parameter Name of the parameter.
  171. * @return Boolean
  172. */
  173. public function isSetByUser($parameter)
  174. {
  175. return in_array($parameter, $this->userDefined);
  176. }
  177. /**
  178. * {@inheritdoc}
  179. */
  180. protected function getBaseURI()
  181. {
  182. if ($this->scheme === 'unix') {
  183. return "{$this->scheme}://{$this->path}";
  184. }
  185. return "{$this->scheme}://{$this->host}:{$this->port}";
  186. }
  187. /**
  188. * Returns the URI parts that must be omitted when calling __toString().
  189. *
  190. * @return array
  191. */
  192. protected function getDisallowedURIParts()
  193. {
  194. return array('scheme', 'host', 'port', 'password', 'path');
  195. }
  196. /**
  197. * {@inheritdoc}
  198. */
  199. public function toArray()
  200. {
  201. return $this->parameters;
  202. }
  203. /**
  204. * Returns a string representation of the parameters.
  205. *
  206. * @return string
  207. */
  208. public function __toString()
  209. {
  210. $query = array();
  211. $parameters = $this->toArray();
  212. $reject = $this->getDisallowedURIParts();
  213. foreach ($this->userDefined as $param) {
  214. if (in_array($param, $reject) || !isset($parameters[$param])) {
  215. continue;
  216. }
  217. $value = $parameters[$param];
  218. $query[] = "$param=" . ($value === false ? '0' : $value);
  219. }
  220. if (count($query) === 0) {
  221. return $this->getBaseURI();
  222. }
  223. return $this->getBaseURI() . '/?' . implode('&', $query);
  224. }
  225. /**
  226. * {@inheritdoc}
  227. */
  228. public function __sleep()
  229. {
  230. return array('parameters', 'userDefined');
  231. }
  232. /**
  233. * {@inheritdoc}
  234. */
  235. public function __wakeup()
  236. {
  237. self::ensureDefaults();
  238. }
  239. }