Passed
Push — master ( f9d022...66a5c5 )
by Sergei
02:37
created

SimpleRuleHandlerContainer   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 22
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 8
c 0
b 0
f 0
dl 0
loc 22
rs 10
wmc 4

1 Method

Rating   Name   Duplication   Size   Complexity  
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
    /**
17
     * @var array<class-string, RuleHandlerInterface>
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<class-string, RuleHandlerInterface> at position 2 could not be parsed: Unknown type name 'class-string' at position 2 in array<class-string, RuleHandlerInterface>.
Loading history...
18
     */
19
    private array $instances = [];
20
21
    public function resolve(string $className): RuleHandlerInterface
22
    {
23
        if (!class_exists($className)) {
24
            throw new RuleHandlerNotFoundException($className);
25
        }
26
27
        if (array_key_exists($className, $this->instances)) {
28
            return $this->instances[$className];
29
        }
30
31
        if (!is_subclass_of($className, RuleHandlerInterface::class)) {
32
            throw new RuleHandlerInterfaceNotImplementedException($className);
33
        }
34
35
        return $this->instances[$className] = new $className();
36
    }
37
}
38