ClientCluster.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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\Options;
  11. use Predis\Network\IConnectionCluster;
  12. use Predis\Network\PredisCluster;
  13. /**
  14. * Option class that returns a connection cluster to be used by a client.
  15. *
  16. * @author Daniele Alessandri <suppakilla@gmail.com>
  17. */
  18. class ClientCluster extends Option
  19. {
  20. /**
  21. * Checks if the specified value is a valid instance of IConnectionCluster.
  22. *
  23. * @param IConnectionCluster $cluster Instance of a connection cluster.
  24. * @return IConnectionCluster
  25. */
  26. protected function checkInstance($cluster)
  27. {
  28. if (!$cluster instanceof IConnectionCluster) {
  29. throw new \InvalidArgumentException('Instance of Predis\Network\IConnectionCluster expected');
  30. }
  31. return $cluster;
  32. }
  33. /**
  34. * {@inheritdoc}
  35. */
  36. public function filter(IClientOptions $options, $value)
  37. {
  38. if (is_callable($value)) {
  39. return $this->checkInstance(call_user_func($value, $options));
  40. }
  41. $initializer = $this->getInitializer($options, $value);
  42. return $this->checkInstance($initializer());
  43. }
  44. /**
  45. * Returns an initializer for the specified FQN or type.
  46. *
  47. * @param string $fqnOrType Type of cluster or FQN of a class implementing IConnectionCluster.
  48. * @param IClientOptions $options Instance of the client options.
  49. * @return \Closure
  50. */
  51. protected function getInitializer(IClientOptions $options, $fqnOrType)
  52. {
  53. switch ($fqnOrType) {
  54. case 'predis':
  55. return function() { return new PredisCluster(); };
  56. default:
  57. // TODO: we should not even allow non-string values here.
  58. if (is_string($fqnOrType) && !class_exists($fqnOrType)) {
  59. throw new \InvalidArgumentException("Class $fqnOrType does not exist");
  60. }
  61. return function() use($fqnOrType) {
  62. return new $fqnOrType();
  63. };
  64. }
  65. }
  66. /**
  67. * {@inheritdoc}
  68. */
  69. public function getDefault(IClientOptions $options)
  70. {
  71. return new PredisCluster();
  72. }
  73. }