Passed
Push — master ( 3112ca...a45803 )
by Blixit
02:01
created

MessagingMiddleware::supports()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Blixit\EventSourcing\Messaging;
6
7
use function get_class;
8
use function is_array;
9
use function is_callable;
10
11
class MessagingMiddleware implements MessagingMiddlewareInterface
12
{
13
    /** To handle any message */
14
    protected const ALL = MessageInterface::class;
15
16
    /** @var mixed[] $handlers */
17
    protected $handlers;
18
19
    /**
20
     * @param mixed[] $handlers
21
     */
22
    public function __construct(array $handlers)
23
    {
24
        $this->handlers = $handlers;
25
    }
26
27
    public function handle(MessageInterface $message) : void
28
    {
29
        $class = get_class($message);
30
        if (! $this->supports($class)) {
31
            return;
32
        }
33
34
        foreach ($this->handlers as $key => $locatedHandler) {
35
            if ($key !== self::ALL && $class !== $key) {
36
                continue;
37
            }
38
            if (is_callable($locatedHandler)) {
39
                $locatedHandler($message);
40
                continue;
41
            }
42
            if (! is_array($locatedHandler)) {
43
                continue;
44
            }
45
            foreach ($locatedHandler as $handler) {
46
                if (! is_callable($handler)) {
47
                    continue;
48
                }
49
                $handler($message);
50
            }
51
        }
52
    }
53
54
    public function supports(string $class) : bool
55
    {
56
        return isset($this->handlers[$class]);
57
    }
58
}
59