ClientCluster.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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($value)
  39. {
  40. if (is_callable($value)) {
  41. return $this->checkInstance(call_user_func($value));
  42. }
  43. $initializer = $this->getInitializer($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. * @return \Closure
  51. */
  52. protected function getInitializer($fqnOrType)
  53. {
  54. switch ($fqnOrType) {
  55. case 'predis':
  56. return function() { return new PredisCluster(); };
  57. default:
  58. return function() use($fqnOrType) {
  59. return new $fqnOrType();
  60. };
  61. }
  62. }
  63. /**
  64. * {@inheritdoc}
  65. */
  66. public function getDefault()
  67. {
  68. return new PredisCluster();
  69. }
  70. }