CommandHandlerMiddleware::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
c 0
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace League\Tactician\Handler;
6
7
use League\Tactician\Handler\Mapping\CommandToHandlerMapping;
8
use League\Tactician\Middleware;
9
use Psr\Container\ContainerInterface;
10
11
use function get_class;
12
13
/**
14
 * Our basic middleware for executing commands.
15
 *
16
 * Feel free to use this as a starting point for your own middleware! :)
17
 */
18
final class CommandHandlerMiddleware implements Middleware
19
{
20
    private ContainerInterface $container;
21
    private CommandToHandlerMapping $mapping;
22
23 1
    public function __construct(ContainerInterface $container, CommandToHandlerMapping $mapping)
24
    {
25 1
        $this->container = $container;
26 1
        $this->mapping   = $mapping;
27 1
    }
28
29
    /**
30
     * Executes a command and optionally returns a value
31
     *
32
     * @return mixed
33
     */
34 1
    public function execute(object $command, callable $next)
35
    {
36
        // 1. Based on the command we received, get the Handler method to call.
37 1
        $methodToCall = $this->mapping->mapCommandToHandler(get_class($command));
38
39
        // 2.  Retrieve an instance of the Handler from our PSR-11 container
40
        //     This assumes the container id is the same as the class name but
41
        //     you can write your own middleware to change this assumption! :)
42 1
        $handler = $this->container->get($methodToCall->getClassName());
43
44
        // 3. Invoke the correct method on the handler and pass the command
45 1
        return $handler->{$methodToCall->getMethodName()}($command);
46
    }
47
}
48