CallbackStrategy.php 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace Elastica\Connection\Strategy;
  3. use Elastica\Exception\InvalidException;
  4. /**
  5. * Description of CallbackStrategy.
  6. *
  7. * @author chabior
  8. */
  9. class CallbackStrategy implements StrategyInterface
  10. {
  11. /**
  12. * @var callable
  13. */
  14. protected $_callback;
  15. /**
  16. * @param callable $callback
  17. *
  18. * @throws \Elastica\Exception\InvalidException
  19. */
  20. public function __construct($callback)
  21. {
  22. if (!self::isValid($callback)) {
  23. throw new InvalidException(sprintf('Callback should be a callable, %s given!', gettype($callback)));
  24. }
  25. $this->_callback = $callback;
  26. }
  27. /**
  28. * @param array|\Elastica\Connection[] $connections
  29. *
  30. * @return \Elastica\Connection
  31. */
  32. public function getConnection($connections)
  33. {
  34. return call_user_func_array($this->_callback, [$connections]);
  35. }
  36. /**
  37. * @param callable $callback
  38. *
  39. * @return bool
  40. */
  41. public static function isValid($callback)
  42. {
  43. return is_callable($callback);
  44. }
  45. }