Passed
Pull Request — master (#222)
by Alexander
02:58
created

SimpleRuleHandlerContainer   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 24
Duplicated Lines 0 %

Test Coverage

Coverage 77.78%

Importance

Changes 2
Bugs 2 Features 0
Metric Value
wmc 5
eloc 9
c 2
b 2
f 0
dl 0
loc 24
ccs 7
cts 9
cp 0.7778
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A resolve() 0 13 4
A __construct() 0 2 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
use Yiisoft\Validator\Exception\RuleHandlerInterfaceNotImplementedException;
8
use Yiisoft\Validator\Exception\RuleHandlerNotFoundException;
9
use Yiisoft\Validator\Rule\RuleHandlerInterface;
10
11
final class SimpleRuleHandlerContainer implements RuleHandlerResolverInterface
12
{
13
    private array $instances = [];
14
15
    /**
16
     * @param array<class-string> $handlers List of rule handler classes.
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<class-string> at position 2 could not be parsed: Unknown type name 'class-string' at position 2 in array<class-string>.
Loading history...
17
     */
18 518
    public function __construct(private array $handlers = [])
19
    {
20
    }
21
22 28
    public function resolve(string $className): RuleHandlerInterface
23
    {
24 28
        if (!array_key_exists($className, $this->instances)) {
25 28
            if (!in_array($className, $this->handlers, true)) {
26
                throw new RuleHandlerNotFoundException($className);
27
            }
28 28
            if (!is_subclass_of($className, RuleHandlerInterface::class)) {
29
                throw new RuleHandlerInterfaceNotImplementedException($className);
30
            }
31 28
            return $this->instances[$className] = new $className();
32
        }
33
34 6
        return $this->instances[$className];
35
    }
36
}
37