ClientCluster.php 2.8 KB

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