Lines 0.00% 0 / 13
Functions and Methods 0.00% 0 / 4
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
RecordingLogger 0.00% 0 / 13 0.00% 0 / 4 42 0.00% 0 / 1
 __construct 0.00% 0 / 1 0.00% 0 / 1 2
 log 0.00% 0 / 4 0.00% 0 / 1 6
 waitForMessage 0.00% 0 / 5 0.00% 0 / 1 6
 listMessagesAt 0.00% 0 / 3 0.00% 0 / 1 2
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Testing\Logging;
6
7use Amp\DeferredFuture;
8use Amp\Future;
9use Psr\Log\AbstractLogger;
10use Stewart\Testing\Logging\Collection\RecordedLogCollection;
11use Stringable;
12
13final class RecordingLogger extends AbstractLogger
14{
15    public private(set) RecordedLogCollection $records;
16
17    /** @var array<string, DeferredFuture<null>> */
18    private array $awaited = [];
19
20    public function __construct()
21    {
22        $this->records = RecordedLogCollection::empty();
23    }
24
25    /**
26     * @param mixed $level
27     * @param array<mixed> $context
28     */
29    public function log($level, string|Stringable $message, array $context = []): void
30    {
31        $this->records = $this->records->withRecordedLog(new RecordedLog(\is_string($level) ? $level : 'unknown', (string) $message, $context));
32
33        $awaited = $this->awaited[(string) $message] ?? null;
34        unset($this->awaited[(string) $message]);
35        $awaited?->complete();
36    }
37
38    /** @return Future<null> */
39    public function waitForMessage(string $message): Future
40    {
41        if ($this->records->containsWhere(static fn(RecordedLog $record): bool => $record->message === $message)) {
42            return Future::complete();
43        }
44
45        /** @var DeferredFuture<null> $waiter */
46        $waiter = $this->awaited[$message] ?? new DeferredFuture();
47        $this->awaited[$message] = $waiter;
48
49        return $waiter->getFuture();
50    }
51
52    /** @return list<string> */
53    public function listMessagesAt(string $level): array
54    {
55        return $this->records
56            ->filter(static fn(RecordedLog $record): bool => $record->level === $level)
57            ->mapToList(static fn(RecordedLog $record): string => $record->message);
58    }
59}