Passed
Pull Request — master (#222)
by Rustam
11:36
created

SimpleRuleHandlerContainer::resolve()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4.25

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 7
c 1
b 1
f 0
dl 0
loc 13
ccs 6
cts 8
cp 0.75
rs 10
cc 4
nc 4
nop 1
crap 4.25
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
     * @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...
16
     */
17 518
    public function __construct(private array $handlers = [])
18
    {
19
    }
20
21 28
    public function resolve(string $className): RuleHandlerInterface
22
    {
23 28
        if (!array_key_exists($className, $this->instances)) {
24 28
            if (!in_array($className, $this->handlers, true)) {
25
                throw new RuleHandlerNotFoundException($className);
26
            }
27 28
            if (!is_subclass_of($className, RuleHandlerInterface::class)) {
28
                throw new RuleHandlerInterfaceNotImplementedException($className);
29
            }
30 28
            return $this->instances[$className] = new $className();
31
        }
32
33 6
        return $this->instances[$className];
34
    }
35
}
36