Passed
Pull Request — master (#461)
by Sergei
03:12
created

SimpleRuleHandlerContainer::__construct()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 3
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 9
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\RuleHandlerResolver;
6
7
use Yiisoft\Validator\Exception\RuleHandlerInterfaceNotImplementedException;
8
use Yiisoft\Validator\Exception\RuleHandlerNotFoundException;
9
use Yiisoft\Validator\RuleHandlerInterface;
10
use Yiisoft\Validator\RuleHandlerResolverInterface;
11
12
use function array_key_exists;
13
14
final class SimpleRuleHandlerContainer implements RuleHandlerResolverInterface
15
{
16
    public function __construct(
17
        /**
18
         * @var array<string, RuleHandlerInterface>
19
         */
20
        private array $instances = [],
21
    ) {
22
        foreach ($instances as $instance) {
23
            if (!$instance instanceof RuleHandlerInterface) {
24
                throw new RuleHandlerInterfaceNotImplementedException($instance);
25
            }
26
        }
27
    }
28
29
    public function resolve(string $className): RuleHandlerInterface
30
    {
31
        if (array_key_exists($className, $this->instances)) {
32
            return $this->instances[$className];
33
        }
34
35
        if (!class_exists($className)) {
36
            throw new RuleHandlerNotFoundException($className);
37
        }
38
39
        if (!is_subclass_of($className, RuleHandlerInterface::class)) {
40
            throw new RuleHandlerInterfaceNotImplementedException($className);
41
        }
42
43
        return $this->instances[$className] = new $className();
44
    }
45
}
46