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