StrategyFactory.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. namespace Elastica\Connection\Strategy;
  3. use Elastica\Exception\InvalidException;
  4. /**
  5. * Description of StrategyFactory.
  6. *
  7. * @author chabior
  8. */
  9. class StrategyFactory
  10. {
  11. /**
  12. * @param mixed|callable|string|StrategyInterface $strategyName
  13. *
  14. * @throws \Elastica\Exception\InvalidException
  15. *
  16. * @return \Elastica\Connection\Strategy\StrategyInterface
  17. */
  18. public static function create($strategyName)
  19. {
  20. if ($strategyName instanceof StrategyInterface) {
  21. return $strategyName;
  22. }
  23. if (CallbackStrategy::isValid($strategyName)) {
  24. return new CallbackStrategy($strategyName);
  25. }
  26. if (is_string($strategyName)) {
  27. $requiredInterface = '\\Elastica\\Connection\\Strategy\\StrategyInterface';
  28. $predefinedStrategy = '\\Elastica\\Connection\\Strategy\\'.$strategyName;
  29. if (class_exists($predefinedStrategy) && class_implements($predefinedStrategy, $requiredInterface)) {
  30. return new $predefinedStrategy();
  31. }
  32. if (class_exists($strategyName) && class_implements($strategyName, $requiredInterface)) {
  33. return new $strategyName();
  34. }
  35. }
  36. throw new InvalidException('Can\'t create strategy instance by given argument');
  37. }
  38. }