Passed
Push — master ( 03c598...1d0b53 )
by Krisztián
01:58
created

ServiceManager   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 37
dl 0
loc 72
rs 10
c 0
b 0
f 0
wmc 17

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A configure() 0 16 4
A getConfig() 0 3 1
A get() 0 18 5
A getServiceType() 0 7 3
A has() 0 5 3
1
<?php
2
3
namespace PhpCache\ServiceManager;
4
5
use PhpCache\ServiceManager\Exception\NotFoundException;
6
use Psr\Container\ContainerInterface;
7
8
/**
9
 * Description of ServiceManager.
10
 *
11
 * @author dude920228
12
 */
13
class ServiceManager implements ContainerInterface
14
{
15
    private $aliases;
16
    private $config;
17
    private $factories;
18
    private $invokables;
19
20
    public function __construct($config)
21
    {
22
        $this->config = $config;
23
        $this->configure();
24
    }
25
26
    private function configure()
27
    {
28
        if (isset($this->config['services']['aliases'])) {
29
            $this->aliases = $this->config['services']['aliases'];
30
        } else {
31
            $this->aliases = [];
32
        }
33
        if (isset($this->config['services']['factories'])) {
34
            $this->factories = $this->config['services']['factories'];
35
        } else {
36
            $this->factories = [];
37
        }
38
        if (isset($this->config['services']['invokables'])) {
39
            $this->invokables = $this->config['services']['invokables'];
40
        } else {
41
            $this->invokables = [];
42
        }
43
    }
44
45
    public function get($id)
46
    {
47
        if ($this->has($id)) {
48
            $serviceType = $this->getServiceType($id);
49
            if($serviceType == 'alias') {
50
                $service = $this->aliases[$id];;
51
                return $this->get($service);
52
            }
53
            if ($serviceType == 'factory') {
54
                return (new $this->factories[$id]())($this);
55
            }
56
            if ($serviceType == 'invokable') {
57
                return new $this->invokables[$id]();
58
            }
59
        }
60
61
        throw new NotFoundException(
62
            sprintf('Service "%s" couldn\'t be created! Reason: service not found', $id)
63
        );
64
    }
65
66
    private function getServiceType($id)
67
    {
68
        if (array_key_exists($id, $this->aliases)) {
69
            return 'alias';
70
        }
71
72
        return array_key_exists($id, $this->factories) ? 'factory' : 'invokable';
73
    }
74
75
    public function getConfig()
76
    {
77
        return $this->config['config'];
78
    }
79
80
    public function has($id)
81
    {
82
        return array_key_exists($id, $this->aliases) ||
83
        array_key_exists($id, $this->factories) ||
84
        array_key_exists($id, $this->invokables);
85
    }
86
}
87