Completed
Push — master ( bd43fc...8544ff )
by Andrew
08:34 queued 05:49
created

Container::createService()   C

Complexity

Conditions 7
Paths 7

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 7

Importance

Changes 3
Bugs 1 Features 1
Metric Value
c 3
b 1
f 1
dl 0
loc 25
ccs 16
cts 16
cp 1
rs 6.7272
cc 7
eloc 15
nc 7
nop 1
crap 7
1
<?php
2
3
namespace SitePoint\Container;
4
5
use SitePoint\Container\Exception\ContainerException;
6
use SitePoint\Container\Exception\ParameterNotFoundException;
7
use SitePoint\Container\Exception\ServiceNotFoundException;
8
use SitePoint\Container\Reference\ParameterReference;
9
use SitePoint\Container\Reference\ServiceReference;
10
11
/**
12
 * A very simple dependency injection container.
13
 */
14
class Container implements ContainerInterface
15
{
16
    /**
17
     * @var array
18
     */
19
    private $services;
20
21
    /**
22
     * @var array
23
     */
24
    private $parameters;
25
26
    /**
27
     * @var array
28
     */
29
    private $serviceStore;
30
31
    /**
32
     * Constructor for the container.
33
     *
34
     * Entries into the $services array must be an associative array with a
35
     * 'class' key and an optional 'arguments' key. Where present the arguments
36
     * will be passed to the class constructor. If an argument is an instance of
37
     * ContainerService the argument will be replaced with the corresponding
38
     * service from the container before the class is instantiated. If an
39
     * argument is an instance of ContainerParameter the argument will be
40
     * replaced with the corresponding parameter from the container before the
41
     * class is instantiated.
42
     *
43
     * @param array $services   The service definitions.
44
     * @param array $parameters The parameter definitions.
45
     */
46 9
    public function __construct(array $services = [], array $parameters = [])
47
    {
48 9
        $this->services     = $services;
49 9
        $this->parameters   = $parameters;
50 9
        $this->serviceStore = [];
51 9
    }
52
53
    /**
54
     * {@inheritDoc}
55
     */
56 7
    public function get($name)
57
    {
58 7
        if (!$this->has($name)) {
59 1
            throw new ServiceNotFoundException('Service not found: '.$name);
60
        }
61
62
        // If we haven't created it, create it and save to store
63 6
        if (!isset($this->serviceStore[$name])) {
64 6
            $this->serviceStore[$name] = $this->createService($name);
65 1
        }
66
67
        // Return service from store
68 1
        return $this->serviceStore[$name];
69
    }
70
71
    /**
72
     * {@inheritDoc}
73
     */
74 7
    public function has($name)
75
    {
76 7
        return isset($this->services[$name]);
77
    }
78
79
    /**
80
     * {@inheritDoc}
81
     */
82 3
    public function getParameter($name)
83
    {
84 3
        $tokens  = explode('.', $name);
85 3
        $context = $this->parameters;
86
87 3
        while (null !== ($token = array_shift($tokens))) {
88 3
            if (!isset($context[$token])) {
89 2
                throw new ParameterNotFoundException('Parameter not found: '.$name);
90
            }
91
92 2
            $context = $context[$token];
93 2
        }
94
95 2
        return $context;
96
    }
97
98
    /**
99
     * {@inheritDoc}
100
     */
101 1
    public function hasParameter($name)
102
    {
103
        try {
104 1
            $this->getParameter($name);
105 1
        } catch (ParameterNotFoundException $exception) {
106 1
            return false;
107
        }
108
109 1
        return true;
110
    }
111
112
    /**
113
     * Attempt to create a service.
114
     *
115
     * @param string $name The service name.
116
     *
117
     * @return mixed The created service.
118
     *
119
     * @throws ContainerException On failure.
120
     */
121 6
    private function createService($name)
122
    {
123 6
        $entry = &$this->services[$name];
124
125 6
        if (!is_array($entry) || !isset($entry['class'])) {
126 1
            throw new ContainerException($name.' service entry must be an array containing a \'class\' key');
127 5
        } elseif (!class_exists($entry['class'])) {
128 1
            throw new ContainerException($name.' service class does not exist: '.$entry['class']);
129 4
        } elseif (isset($entry['lock'])) {
130 1
            throw new ContainerException($name.' contains circular reference');
131
        }
132
133 4
        $entry['lock'] = true;
134
135 4
        $arguments = isset($entry['arguments']) ? $this->resolveArguments($name, $entry['arguments']) : [];
0 ignored issues
show
Documentation introduced by
$entry['arguments'] is of type boolean, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
136
137 3
        $reflector = new \ReflectionClass($entry['class']);
138 3
        $service = $reflector->newInstanceArgs($arguments);
139
140 3
        if (isset($entry['calls'])) {
141 3
            $this->initializeService($service, $name, $entry['calls']);
0 ignored issues
show
Documentation introduced by
$entry['calls'] is of type boolean, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
142 1
        }
143
144 1
        return $service;
145
    }
146
147
    /**
148
     * Resolve argument definitions into an array of arguments.
149
     *
150
     * @param string $name                The service name.
151
     * @param array  $argumentDefinitions The service arguments definition.
152
     *
153
     * @return array The service constructor arguments.
154
     *
155
     * @throws ContainerException On failure.
156
     */
157 4
    private function resolveArguments($name, array $argumentDefinitions)
0 ignored issues
show
Unused Code introduced by
The parameter $name is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
158
    {
159 4
        $arguments = [];
160
161 4
        foreach ($argumentDefinitions as $argumentDefinition) {
162 4
            if ($argumentDefinition instanceof ServiceReference) {
163 2
                $argumentServiceName = $argumentDefinition->getName();
164
165 2
                $arguments[] = $this->get($argumentServiceName);
166 3
            } elseif ($argumentDefinition instanceof ParameterReference) {
167 1
                $argumentParameterName = $argumentDefinition->getName();
168
169 1
                $arguments[] = $this->getParameter($argumentParameterName);
170 1
            } else {
171 3
                $arguments[] = $argumentDefinition;
172
            }
173 3
        }
174
175 3
        return $arguments;
176
    }
177
178
    /**
179
     * Initialize a service using the call definitions.
180
     *
181
     * @param object $service         The service.
182
     * @param string $name            The service name.
183
     * @param array  $callDefinitions The service calls definition.
184
     *
185
     * @throws ContainerException On failure.
186
     */
187 3
    private function initializeService($service, $name, array $callDefinitions)
188
    {
189 3
        foreach ($callDefinitions as $callDefinition) {
190 3
            if (!is_array($callDefinition) || !isset($callDefinition['method'])) {
191 1
                throw new ContainerException($name.' service calls must be arrays containing a \'method\' key');
192 2
            } elseif (!is_callable([$service, $callDefinition['method']])) {
193 1
                throw new ContainerException($name.' service asks for call to uncallable method: '.$callDefinition['method']);
194
            }
195
196 1
            $arguments = isset($callDefinition['arguments']) ? $this->resolveArguments($name, $callDefinition['arguments']) : [];
197
198 1
            call_user_func_array([$service, $callDefinition['method']], $arguments);
199 1
        }
200 1
    }
201
}
202