Passed
Pull Request — master (#35)
by Akmal
01:51
created

Di::getMethodParams()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 10
nc 4
nop 2
dl 0
loc 19
rs 9.9332
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace OpenEngine\Mika\Core\Components\Di;
4
5
use OpenEngine\Mika\Core\Components\Di\Exceptions\MethodNotFoundException;
6
use OpenEngine\Mika\Core\Components\Di\Exceptions\MissingMethodArgumentException;
7
use OpenEngine\Mika\Core\Components\Di\Exceptions\ServiceNotFoundException;
8
use OpenEngine\Mika\Core\Components\Di\Interfaces\DiConfigInterface;
9
use OpenEngine\Mika\Core\Components\Di\Traits\CreateObjectTrait;
10
use Psr\Container\ContainerInterface;
11
12
class Di implements ContainerInterface
13
{
14
    use CreateObjectTrait;
0 ignored issues
show
Bug introduced by
The trait OpenEngine\Mika\Core\Com...raits\CreateObjectTrait requires the property $name which is not provided by OpenEngine\Mika\Core\Components\Di\Di.
Loading history...
15
16
    /**
17
     * Created services
18
     *
19
     * @var object[]
20
     */
21
    private $singletons;
22
23
    /**
24
     * Registered service names
25
     *
26
     * @var string[]
27
     */
28
    private $services;
29
30
    /**
31
     * Di constructor.
32
     * @param DiConfigInterface $diConfig
33
     */
34
    public function __construct(DiConfigInterface $diConfig)
35
    {
36
        $diConfig->registerObject(ContainerInterface::class, $this);
37
        $this->services = $diConfig->getServices();
38
        $this->singletons = $diConfig->getServiceObjects();
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     * @throws MethodNotFoundException
44
     * @throws MissingMethodArgumentException
45
     */
46
    public function get($id): object
47
    {
48
        if (!$this->has($id)) {
49
            throw new ServiceNotFoundException('Service ' . $id . ' is not found');
50
        }
51
52
        $singleton = $this->getSingleton($id);
53
54
        if ($singleton !== null) {
55
            return $singleton;
56
        }
57
58
        return $this->createObject($this->getService($id));
59
    }
60
61
    /**
62
     * @inheritdoc
63
     */
64
    public function has($id): bool
65
    {
66
        return $this->getService($id) !== null;
67
    }
68
69
    /**
70
     * @param string $id
71
     * @return string|null
72
     */
73
    private function getService(string $id): ?string
74
    {
75
        if (isset($this->services[$id])) {
76
            return $this->services[$id];
77
        }
78
79
        return null;
80
    }
81
82
    /**
83
     * @param string $id
84
     * @return \object|null
85
     */
86
    private function getSingleton(string $id): ?object
87
    {
88
        if (isset($this->singletons[$id])) {
89
            return $this->singletons[$id];
90
        }
91
92
        return null;
93
    }
94
}
95