Passed
Push — master ( fa0473...13dd59 )
by Sergei
02:36
created

SimpleRuleHandlerContainer   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 10
c 0
b 0
f 0
dl 0
loc 30
rs 10
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 3
A resolve() 0 15 4
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