Completed
Pull Request — master (#366)
by Beñat
05:52 queued 01:06
created

Projector::register()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Kreta package.
5
 *
6
 * (c) Beñat Espiña <[email protected]>
7
 * (c) Gorka Laucirica <[email protected]>
8
 *
9
 * For the full copyright and license information, please view the LICENSE
10
 * file that was distributed with this source code.
11
 */
12
13
declare(strict_types=1);
14
15
namespace Kreta\SharedKernel\Projection;
16
17
use Kreta\SharedKernel\Domain\Model\DomainEventCollection;
18
use Kreta\SharedKernel\Domain\Model\Exception;
19
20
final class Projector
21
{
22
    private $eventHandlers;
23
    private static $instance = null;
24
25
    public static function instance() : self
26
    {
27
        if (null === self::$instance) {
28
            self::$instance = new self();
29
        }
30
31
        return self::$instance;
32
    }
33
34
    private function __construct()
35
    {
36
        $this->eventHandlers = [];
37
    }
38
39
    public function __clone()
40
    {
41
        throw new Exception('Clone is not supported');
42
    }
43
44
    public function register(array $eventHandlers)
45
    {
46
        foreach ($eventHandlers as $eventHandler) {
47
            $this->add($eventHandler);
48
        }
49
    }
50
51
    private function add(EventHandler $eventHandler)
52
    {
53
        $this->eventHandlers[$eventHandler->eventType()] = $eventHandler;
54
    }
55
56
    public function project(DomainEventCollection $events) : void
57
    {
58
        foreach ($events->toArray() as $event) {
59
            if (isset($this->eventHandlers[get_class($event)])) {
60
                $this->eventHandlers[get_class($event)]->handle($event);
61
            }
62
        }
63
    }
64
}
65