Completed
Push — master ( c54dd1...7d6afc )
by Douglas
03:28
created

AbstractBus::post()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 0
cts 5
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
crap 2
1
<?php
2
3
/**
4
 * (c) 2018 Douglas Reith.
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
declare(strict_types=1);
10
11
namespace Reith\ToyRobot\Infrastructure\Bus;
12
13
use Assert\Assertion;
14
use Reith\ToyRobot\Messaging\BusInterface;
15
16
abstract class AbstractBus implements BusInterface
17
{
18
    // Message handlers
19
    private $handlers;
20
21
    /**
22
     * @param mixed $handler
23
     */
24
    public function registerHandler($handler): AbstractBus
25
    {
26
        // Expect the handler to be an object
27
        Assertion::isObject($handler);
28
29
        $this->handlers[] = new HandlerWrapper($handler);
30
31
        return $this;
32
    }
33
34
    /**
35
     * @param mixed $message
36
     * @throws \Assert\AssertionFailedException
37
     */
38
    public function post($message): void
39
    {
40
        // Expect the message to be an object to use reflection
41
        // and match the handler method
42
        Assertion::isObject($message);
43
44
        $messageHandler = $this->findHandler($message);
45
46
        // Run the command
47
        call_user_func($messageHandler, $message);
48
    }
49
50
    /**
51
     * @return callable
52
     * @throws \RuntimeException
53
     */
54
    private function findHandler($message): callable
55
    {
56
        // In this implementation the first handler wins but
57
        // actually we would want to fail if there is more than
58
        // one for Commands and Queries
59
        foreach ($this->handlers as $handler) {
60
            if ($callable = $handler->getCallable($message)) {
61
                return $callable;
62
            }
63
        }
64
65
        throw new \RuntimeException(
66
            sprintf('No handler was found for message [%s]', get_class($message))
67
        );
68
    }
69
}
70