CallableLocator::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
namespace League\Tactician\Handler\Locator;
3
4
use League\Tactician\Exception\MissingHandlerException;
5
6
/**
7
 * This locator loads Handlers from a provided callable.
8
 *
9
 * At first glance, this might seem fairly useless but it's actually very
10
 * useful to encapsulate DI containers without having to write a custom adapter
11
 * for each one.
12
 *
13
 * Let's say you have a Symfony container or similar that works via a 'get'
14
 * method. You can pass in an array style callable such as:
15
 *
16
 *     $locator = new CallableLocator([$container, 'get'])
17
 *
18
 * This is easy to set up and will now automatically pipe the command name
19
 * straight through to the $container->get() method without having to write
20
 * the custom locator.
21
 *
22
 * Naturally, you can also pass in closures for further behavior tweaks.
23
 */
24
class CallableLocator implements HandlerLocator
25
{
26
    /**
27
     * @var callable
28
     */
29
    private $callable;
30
31
    /**
32
     * @param callable $callable
33
     */
34 4
    public function __construct(callable $callable)
35
    {
36 4
        $this->callable = $callable;
37 4
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42 4
    public function getHandlerForCommand($commandName)
43
    {
44 4
        $callable = $this->callable;
45 4
        $handler = $callable($commandName);
46
47
        // Odds are the callable threw an exception but it always pays to check
48 3
        if ($handler === null) {
49 1
            throw MissingHandlerException::forCommand($commandName);
50
        }
51
52 2
        return $handler;
53
    }
54
}
55