Passed
Pull Request — master (#293)
by
unknown
02:31
created

SimpleRuleHandlerContainer::resolve()   A

Complexity

Conditions 6
Paths 7

Size

Total Lines 25
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6.0163

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 13
c 2
b 0
f 0
dl 0
loc 25
ccs 12
cts 13
cp 0.9231
rs 9.2222
cc 6
nc 7
nop 1
crap 6.0163
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 $e) {
35 3
            if ($e->getMessage() !== 'Unknown named parameter $translator') {
36
                throw $e;
37
            }
38
39 3
            $classInstance = new $className();
40
        }
41
42 101
        if (!$classInstance instanceof RuleHandlerInterface) {
43 1
            throw new RuleHandlerInterfaceNotImplementedException($className);
44
        }
45
46 100
        return $this->instances[$className] = $classInstance;
47
    }
48
}
49