Passed
Pull Request — master (#27)
by Rasmus
12:10
created

ContainerResolver::__invoke()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

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