Passed
Pull Request — master (#243)
by Jesús
09:27
created

Locator::isInterface()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\Framework\Container;
6
7
use Gacela\Framework\ClassResolver\GlobalInstance\AnonymousGlobal;
8
9
final class Locator
10
{
11
    private static ?Locator $instance = null;
12
13
    /** @var array<string, mixed> */
14
    private array $instanceCache = [];
15
16 3
    private function __construct()
17
    {
18 3
    }
19
20
    /**
21
     * @codeCoverageIgnore
22
     */
23
    private function __clone()
24
    {
25
    }
26
27 3
    public static function getInstance(): self
28
    {
29 3
        if (self::$instance === null) {
30 3
            self::$instance = new self();
31
        }
32
33 3
        return self::$instance;
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::instance could return the type null which is incompatible with the type-hinted return Gacela\Framework\Container\Locator. Consider adding an additional type-check to rule them out.
Loading history...
34
    }
35
36 2
    public static function resetInstance(): void
37
    {
38 2
        self::$instance = null;
39
    }
40
41
    /**
42
     * @template T
43
     *
44
     * @param class-string<T> $className
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string<T> at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string<T>.
Loading history...
45
     *
46
     * @return T|null
47
     */
48 3
    public function get(string $className)
49
    {
50 3
        if (isset($this->instanceCache[$className])) {
51
            /** @var T $instance */
52 1
            $instance = $this->instanceCache[$className];
53
54 1
            return $instance;
55
        }
56
57 3
        $locatedInstance = AnonymousGlobal::getByClassName($className)
58 3
            ?? $this->newInstance($className);
59
60
        /** @psalm-suppress MixedAssignment */
61 3
        $this->instanceCache[$className] = $locatedInstance;
62
63 3
        return $locatedInstance;
64
    }
65
66
    /**
67
     * @template T
68
     *
69
     * @param class-string<T> $className
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string<T> at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string<T>.
Loading history...
70
     *
71
     * @return T|null
72
     */
73 3
    private function newInstance(string $className)
74
    {
75 3
        if (class_exists($className)) {
76
            /** @psalm-suppress MixedMethodCall */
77 2
            return new $className();
78
        }
79
80 1
        return null;
81
    }
82
}
83