Completed
Pull Request — master (#421)
by Jonas
03:17
created

relocateEventToCanonicalPlace()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
namespace CultuurNet\UDB3\Event;
4
5
use Broadway\CommandHandling\CommandBusInterface;
6
use Broadway\Domain\DomainMessage;
7
use Broadway\EventHandling\EventListenerInterface;
8
use CultuurNet\UDB3\Event\Commands\UpdateLocation;
9
use CultuurNet\UDB3\Event\Events\EventCreated;
10
use CultuurNet\UDB3\Event\Events\LocationUpdated;
11
use CultuurNet\UDB3\Event\ValueObjects\LocationId;
12
use CultuurNet\UDB3\Place\CanonicalPlaceRepository;
13
14
final class RelocateEventToCanonicalPlace implements EventListenerInterface
15
{
16
    /**
17
     * @var CommandBusInterface
18
     */
19
    private $commandBus;
20
21
    /**
22
     * @var CanonicalPlaceRepository
23
     */
24
    private $canonicalPlaceRepository;
25
26
    public function __construct(CommandBusInterface $commandBus, CanonicalPlaceRepository $canonicalPlaceRepository)
27
    {
28
        $this->commandBus = $commandBus;
29
        $this->canonicalPlaceRepository = $canonicalPlaceRepository;
30
    }
31
32
    public function handle(DomainMessage $domainMessage)
33
    {
34
        $event = $domainMessage->getPayload();
35
        switch (true) {
36
            case $event instanceof EventCreated:
37
                $this->handleEventCreated($event);
38
                break;
39
            case $event instanceof LocationUpdated:
40
                $this->handleLocationUpdated($event);
41
                break;
42
            default:
43
                return;
44
        }
45
    }
46
47
    private function handleEventCreated(EventCreated $event): void
48
    {
49
        $this->relocateEventToCanonicalPlace($event->getEventId(), $event->getLocation());
50
    }
51
52
    private function handleLocationUpdated(LocationUpdated $event): void
53
    {
54
        $this->relocateEventToCanonicalPlace($event->getItemId(), $event->getLocationId());
55
    }
56
57
    private function relocateEventToCanonicalPlace(string $eventId, LocationId $locationId): void
58
    {
59
        $place = $this->canonicalPlaceRepository->findCanonicalFor($locationId->toNative());
60
        $canonicalPlace = new LocationId($place->getAggregateRootId());
61
        if ($locationId->sameValueAs($canonicalPlace)) {
62
            return;
63
        }
64
65
        $this->commandBus->dispatch(new UpdateLocation($eventId, $canonicalPlace));
66
    }
67
}
68