Completed
Push — master ( a99541...e1f08c )
by Muhammad Kashif
42:53 queued 17:55
created

Container   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 86.96%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 9
c 1
b 0
f 1
lcom 1
cbo 2
dl 0
loc 72
ccs 20
cts 23
cp 0.8696
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A get() 0 12 3
A has() 0 4 1
A createService() 0 17 4
1
<?php
2
3
namespace Gr8abbasi\Container;
4
5
use Interop\Container\ContainerInterface;
6
use Gr8abbasi\Container\Exception\NotFoundException;
7
use Gr8abbasi\Container\Exception\ContainerException;
8
9
/**
10
 * Container Class
11
 */
12
class Container implements ContainerInterface
13
{
14
    /**
15
     * @var array
16
     */
17
    private $services;
18
19
    /**
20
     * @var array
21
     */
22
    private $serviceStore;
23
24
    /**
25
     * Constructor for Container
26
     *
27
     * @param array $services
28
     */
29 4
    public function __construct(array $services = [])
30
    {
31 4
        $this->services = $services;
32 4
        $this->serviceStore = [];
33 4
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38 3
    public function get($name)
39
    {
40 3
        if (!$this->has($name)) {
41 1
            throw new NotFoundException('Service not found: ' . $name);
42
        }
43
44 2
        if (!isset($this->serviceStore[$name])) {
45 2
            $this->serviceStore[$name] = $this->createService($name);
46 1
        }
47
48 1
        return $this->serviceStore[$name];
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54 3
    public function has($name)
55
    {
56 3
        return isset($this->services[$name]);
57
    }
58
59
    /**
60
     * Create service instance
61
     *
62
     * @param string $name
63
     *
64
     * @return mixed created service
65
     */
66 2
    private function createService($name)
67
    {
68 2
        if (!isset($this->services[$name]) || empty($this->services[$name])) {
69 1
            throw new ContainerException(
70
                'Service should be an array with key value pair: ' . $name
71 1
            );
72
        }
73
74 1
        if (!class_exists($this->services[$name]['class'])) {
75
            throw new ContainerException(
76
                'Class does not exists: ' . $this->services[$name]['class']
77
            );
78
        }
79
80 1
        $service = new \ReflectionClass($this->services[$name]['class']);
81 1
        return $service->newInstance();
82
    }
83
}
84