ClientCluster.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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(
  30. 'Instance of Predis\Network\IConnectionCluster expected'
  31. );
  32. }
  33. return $cluster;
  34. }
  35. /**
  36. * {@inheritdoc}
  37. */
  38. public function validate(IClientOptions $options, $value)
  39. {
  40. if (is_callable($value)) {
  41. return $this->checkInstance(call_user_func($value));
  42. }
  43. $initializer = $this->getInitializer($options, $value);
  44. return $this->checkInstance($initializer());
  45. }
  46. /**
  47. * Returns an initializer for the specified FQN or type.
  48. *
  49. * @param string $fqnOrType Type of cluster of FQN of a class implementing IConnectionCluster.
  50. * @param IClientOptions $options Instance of the client options.
  51. * @return \Closure
  52. */
  53. protected function getInitializer(IClientOptions $options, $fqnOrType)
  54. {
  55. switch ($fqnOrType) {
  56. case 'predis':
  57. return function() { return new PredisCluster(); };
  58. default:
  59. return function() use($fqnOrType) {
  60. return new $fqnOrType();
  61. };
  62. }
  63. }
  64. /**
  65. * {@inheritdoc}
  66. */
  67. public function getDefault(IClientOptions $options)
  68. {
  69. return new PredisCluster();
  70. }
  71. }