Passed
Push — master ( 9ec1b2...596585 )
by Juuso
03:58
created

GenericStrategyBasedFactory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
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