1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace leinonen\Yii2Monolog\Factories; |
4
|
|
|
|
5
|
|
|
use Yii; |
6
|
|
|
use yii\base\InvalidConfigException; |
7
|
|
|
use leinonen\Yii2Monolog\CreationStrategies\StrategyResolver; |
8
|
|
|
use leinonen\Yii2Monolog\CreationStrategies\CreationStrategyInterface; |
9
|
|
|
|
10
|
|
|
class GenericStrategyBasedFactory |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @var StrategyResolver |
14
|
|
|
*/ |
15
|
|
|
private $strategyResolver; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Initiates a new AbstractStrategyBasedFactory. |
19
|
|
|
* |
20
|
|
|
* @param StrategyResolver $strategyResolver |
21
|
|
|
*/ |
22
|
2 |
|
public function __construct(StrategyResolver $strategyResolver) |
23
|
|
|
{ |
24
|
2 |
|
$this->strategyResolver = $strategyResolver; |
25
|
2 |
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Makes the given class with the given strategy and config. |
29
|
|
|
* |
30
|
|
|
* @param string $className |
31
|
|
|
* @param array $config |
32
|
|
|
* @param CreationStrategyInterface|null $strategy If no strategy given the correct strategy will be resolved using |
33
|
|
|
* StrategyResolver |
34
|
|
|
* |
35
|
|
|
* @see StrategyResolver::resolve() |
36
|
|
|
* |
37
|
|
|
* @return mixed |
38
|
|
|
* @throws InvalidConfigException |
39
|
|
|
*/ |
40
|
2 |
|
public function makeWithStrategy( |
41
|
|
|
string $className, |
42
|
|
|
array $config = [], |
43
|
|
|
CreationStrategyInterface $strategy = null |
44
|
|
|
) { |
45
|
2 |
|
if ($strategy === null) { |
46
|
2 |
|
$strategy = $this->strategyResolver->resolve($className); |
47
|
|
|
} |
48
|
2 |
|
$this->validateConfigParameters($strategy, $className, $config); |
49
|
|
|
|
50
|
1 |
|
return Yii::$container->get($className, $strategy->getConstructorParameters($config)); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Validates the given config against the given strategy. |
55
|
|
|
* |
56
|
|
|
* @param CreationStrategyInterface $strategy |
57
|
|
|
* @param string $className |
58
|
|
|
* @param array $config |
59
|
|
|
* |
60
|
|
|
* @throws InvalidConfigException |
61
|
|
|
*/ |
62
|
2 |
|
private function validateConfigParameters( |
63
|
|
|
CreationStrategyInterface $strategy, |
64
|
|
|
string $className, |
65
|
|
|
array $config |
66
|
|
|
): void { |
67
|
2 |
|
$requiredParameters = $strategy->getRequiredParameters(); |
68
|
2 |
|
$givenParameters = \array_keys($config); |
69
|
|
|
|
70
|
2 |
|
foreach ($requiredParameters as $requiredParameter) { |
71
|
2 |
|
if (! \in_array($requiredParameter, $givenParameters, true)) { |
72
|
1 |
|
throw new InvalidConfigException( |
73
|
2 |
|
"The parameter '{$requiredParameter}' is required for {$className}" |
74
|
|
|
); |
75
|
|
|
} |
76
|
|
|
} |
77
|
1 |
|
} |
78
|
|
|
} |
79
|
|
|
|