NaiveContainer::has()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 10
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 21
rs 9.6111
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace inroutephp\inroute\Runtime;
6
7
use inroutephp\inroute\Runtime\Exception\ServiceNotFoundException;
8
use Psr\Container\ContainerInterface;
9
10
final class NaiveContainer implements ContainerInterface
11
{
12
    /**
13
     * @var array<string, mixed>
14
     */
15
    private $services = [];
16
17
    public function get($id)
18
    {
19
        $id = (string)$id;
20
21
        if (!$this->has($id)) {
22
            throw new ServiceNotFoundException("Unable to instantiate '$id'");
23
        }
24
25
        if (!isset($this->services[$id])) {
26
            $this->services[$id] = new $id;
27
        }
28
29
        return $this->services[$id];
30
    }
31
32
    public function has($id)
33
    {
34
        $id = (string)$id;
35
36
        if (!class_exists($id)) {
37
            return false;
38
        }
39
40
        $classReflector = new \ReflectionClass($id);
41
42
        if (!$classReflector->isInstantiable()) {
43
            return false;
44
        }
45
46
        $constructorReflector = $classReflector->getConstructor();
47
48
        if ($constructorReflector && $constructorReflector->getNumberOfRequiredParameters()) {
49
            return false;
50
        }
51
52
        return true;
53
    }
54
}
55