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 mixed|callable|string|StrategyInterface $strategyName
16     *
17     * @throws InvalidException
18     *
19     * @return StrategyInterface
20     */
21    public static function create($strategyName): StrategyInterface
22    {
23        if ($strategyName instanceof StrategyInterface) {
24            return $strategyName;
25        }
26
27        if (\is_callable($strategyName)) {
28            return new CallbackStrategy($strategyName);
29        }
30
31        if (\is_string($strategyName)) {
32            $requiredInterface = StrategyInterface::class;
33            $predefinedStrategy = '\\Elastica\\Connection\\Strategy\\'.$strategyName;
34
35            if (\class_exists($predefinedStrategy) && \class_implements($predefinedStrategy, $requiredInterface)) {
36                return new $predefinedStrategy();
37            }
38
39            if (\class_exists($strategyName) && \class_implements($strategyName, $requiredInterface)) {
40                return new $strategyName();
41            }
42        }
43
44        throw new InvalidException('Can\'t create strategy instance by given argument');
45    }
46}
47