NaiveContainer   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 43
rs 10
wmc 8

2 Methods

Rating   Name   Duplication   Size   Complexity  
A has() 0 21 5
A get() 0 13 3
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