InMemoryEventPublisher::assertEventData()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 9
rs 10
1
<?php
2
3
namespace App\Tests\TestUtils\Events;
4
5
use App\Infrastructure\Events\Api\ApplicationEventPublisherInterface;
6
use App\Infrastructure\Events\ApplicationOutboundEvent;
7
use DusanKasan\Knapsack\Collection;
8
use PHPUnit\Framework\Assert;
9
10
class InMemoryEventPublisher implements ApplicationEventPublisherInterface
11
{
12
    /**
13
     * @var Collection<ApplicationOutboundEvent>
14
     */
15
    private static Collection $publishedEvents;
16
17
    public function __construct()
18
    {
19
        InMemoryEventPublisher::clear();
20
    }
21
22
23
    public function publish(ApplicationOutboundEvent $event)
24
    {
25
        InMemoryEventPublisher::$publishedEvents = InMemoryEventPublisher::$publishedEvents->append($event);
26
    }
27
28
    public static function clear()
29
    {
30
        InMemoryEventPublisher::$publishedEvents = Collection::from([]);
31
    }
32
33
    /**
34
     * @param string $eventClass
35
     * @return array<ApplicationOutboundEvent>
36
     */
37
    public static function get(string $eventClass): array
38
    {
39
        return array_values(
40
            InMemoryEventPublisher::$publishedEvents
41
                ->filter(function ($event) use ($eventClass) {
42
                    return $event::class == $eventClass;
43
                })
44
                ->toArray()
45
        );
46
    }
47
48
    public static function assertEventData(array $expectedData, ApplicationOutboundEvent $event)
49
    {
50
        $eventData = $event->getData();
51
        foreach ($expectedData as $key => $value) {
52
            Assert::assertTrue(isset($eventData[$key]), "Missing Event Data Key: $key");
53
            if (self::isNotNullCheck($key)) {
54
                Assert::assertNotNull($eventData[$key], "Null Event Data Key: $key");
55
            } else {
56
                Assert::assertEquals($expectedData[$key], $eventData[$key], "Invalid Event Data Key: $key");
57
            }
58
59
        }
60
    }
61
62
    private static function isNotNullCheck(string $key): bool
63
    {
64
        return str_ends_with($key, 'Id') || str_ends_with($key, 'At');
65
    }
66
67
68
}