Completed
Pull Request — master (#366)
by Beñat
04:53
created

Projector::add()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
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
use Kreta\SharedKernel\Domain\ReadEvent\EventHandler;
20
21
final class Projector
22
{
23
    private $eventHandlers;
24
    private static $instance = null;
25
26
    public static function instance() : self
27
    {
28
        if (null === self::$instance) {
29
            self::$instance = new self();
30
        }
31
32
        return self::$instance;
33
    }
34
35
    private function __construct()
36
    {
37
        $this->eventHandlers = [];
38
    }
39
40
    public function __clone()
41
    {
42
        throw new Exception('Clone is not supported');
43
    }
44
45
    public function register(array $eventHandlers)
46
    {
47
        foreach ($eventHandlers as $eventHandler) {
48
            $this->add($eventHandler);
49
        }
50
    }
51
52
    private function add(EventHandler $eventHandler)
53
    {
54
        $this->eventHandlers[$eventHandler->isSubscribeTo()] = $eventHandler;
55
    }
56
57
    public function project(DomainEventCollection $events) : void
58
    {
59
        foreach ($events->toArray() as $event) {
60
            if (isset($this->eventHandlers[get_class($event)])) {
61
                $this->eventHandlers[get_class($event)]->handle($event);
62
            }
63
        }
64
    }
65
}
66