Services::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Devmachine\Bundle\ServicesInjectorBundle\Request;
4
5
use Devmachine\Bundle\ServicesInjectorBundle\ServiceLocator\ServiceLocator;
6
7
final class Services
8
{
9
    private $aliases = [];
10
    private $locator;
11
12
    /**
13
     * @param array          $aliases
14
     * @param ServiceLocator $locator
15
     */
16
    public function __construct(array $aliases, ServiceLocator $locator)
17
    {
18
        $this->aliases = $aliases;
19
        $this->locator = $locator;
20
    }
21
22
    /**
23
     * @param string $alias
24
     *
25
     * @return object
26
     *
27
     * @throws \InvalidArgumentException
28
     */
29
    public function get($alias)
30
    {
31
        if (!isset($this->aliases[$alias])) {
32
            throw new \InvalidArgumentException(sprintf('Service with alias "%s" is not registered.', $alias));
33
        }
34
35
        $serviceId = $this->aliases[$alias];
36
37
        return $this->locator->get($serviceId);
38
    }
39
40
    /**
41
     * @param string $method
42
     * @param array  $args
43
     *
44
     * @return object
45
     *
46
     * @throws \BadMethodCallException
47
     */
48
    public function __call($method, array $args)
49
    {
50
        if (substr($method, 0, 3) !== 'get') {
51
            throw new \BadMethodCallException(sprintf('Invalid method call %s::%s', get_class($this), $method));
52
        }
53
54
        // https://github.com/doctrine/inflector/blob/master/lib/Doctrine/Common/Inflector/Inflector.php
55
        $alias = strtolower(preg_replace('~(?<=\\w)([A-Z])~', '_$1', substr($method, 3)));
56
57
        return $this->get($alias);
58
    }
59
}
60