Passed
Pull Request — master (#293)
by Alexander
04:27 queued 01:59
created

SimpleRuleHandlerContainer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 0
c 0
b 0
f 0
dl 0
loc 2
ccs 1
cts 1
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
use Error;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Yiisoft\Validator\Error. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
8
use Yiisoft\Translator\TranslatorInterface;
9
use Yiisoft\Validator\Exception\RuleHandlerInterfaceNotImplementedException;
10
use Yiisoft\Validator\Exception\RuleHandlerNotFoundException;
11
12
use function array_key_exists;
13
14
final class SimpleRuleHandlerContainer implements RuleHandlerResolverInterface
15
{
16
    private array $instances = [];
17
18 657
    public function __construct(private TranslatorInterface $translator)
19
    {
20
    }
21
22 115
    public function resolve(string $className): RuleHandlerInterface
23
    {
24 115
        if (!class_exists($className)) {
25 1
            throw new RuleHandlerNotFoundException($className);
26
        }
27
28 114
        if (array_key_exists($className, $this->instances)) {
29 35
            return $this->instances[$className];
30
        }
31
32
        try {
33 101
            $classInstance = new $className(translator: $this->translator);
34 3
        } catch (Error) {
35 3
            $classInstance = new $className();
36
        }
37
38 101
        if (!$classInstance instanceof RuleHandlerInterface) {
39 1
            throw new RuleHandlerInterfaceNotImplementedException($className);
40
        }
41
42 100
        return $this->instances[$className] = $classInstance;
43
    }
44
}
45