Completed
Pull Request — master (#8)
by Rasmus
03:13
created

ContainerResolver::__invoke()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 1
crap 3
1
<?php
2
3
namespace mindplay\middleman;
4
5
use Interop\Container\ContainerInterface;
6
use RuntimeException;
7
8
/**
9
 * Optionally, pass this as `$resolver` to {@see Dispatcher::__construct()} to provide
10
 * integration with a dependency injection container - for example:
11
 *
12
 *     $dispatcher = new Dispatcher(
13
 *         [
14
 *             RouterMiddleware::class,
15
 *             ErrorMiddleware::class,
16
 *         ],
17
 *         new InteropResolver($container)
18
 *     );
19
 *
20
 * Note that this resolver will ignore any middleware component that is not a string - so you
21
 * can mix component names with regular middleware closures, callable objects, and so on.
22
 *
23
 * You can use class-names or other component names, depending on what your container supports.
24
 *
25
 * @link https://github.com/container-interop/container-interop
26
 */
27
class ContainerResolver
28
{
29
    /**
30
     * @var ContainerInterface
31
     */
32
    private $container;
33
34
    /**
35
     * @param ContainerInterface $container
36
     */
37 1
    public function __construct(ContainerInterface $container)
38
    {
39 1
        $this->container = $container;
40 1
    }
41
42 1
    public function __invoke($name)
43
    {
44 1
        if (! is_string($name)) {
45 1
            return $name; // nothing to resolve (may be a closure or other callable middleware object)
46
        }
47
48 1
        if ($this->container->has($name)) {
49 1
            return $this->container->get($name);
50
        }
51
52 1
        throw new RuntimeException("unable to resolve middleware component name: {$name}");
53
    }
54
}
55