Lines
100.00%
16 / 16
Functions and Methods
100.00%
4 / 4
Classes and Traits
100.00%
1 / 1
| Name | Lines | Functions and Methods | CRAP | Classes and Traits | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Emitter | 100.00% | 16 / 16 | 100.00% | 4 / 4 | 5 | 100.00% | 1 / 1 | |||
| __construct | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| emit | 100.00% | 7 / 7 | 100.00% | 1 / 1 | 1 | |||||
| messageLoggerContext | 100.00% | 6 / 6 | 100.00% | 1 / 1 | 1 | |||||
| log | 100.00% | 2 / 2 | 100.00% | 1 / 1 | 2 | |||||
| 1 | <?php | |
| 2 | ||
| 3 | declare(strict_types=1); | |
| 4 | ||
| 5 | namespace Tomaj\Hermes; | |
| 6 | ||
| 7 | use Psr\Log\LoggerInterface; | |
| 8 | use Psr\Log\LogLevel; | |
| 9 | use Tomaj\Hermes\Driver\DriverInterface; | |
| 10 | ||
| 11 | final readonly class Emitter implements EmitterInterface | |
| 12 | { | |
| 13 | /** | |
| 14 | * Create new Emitter | |
| 15 | */ | |
| 16 | public function __construct( | |
| 17 | private DriverInterface $driver, | |
| 18 | private ?LoggerInterface $logger = null, | |
| 19 | ) {} | |
| 20 | ||
| 21 | /** | |
| 22 | * @throws Driver\UnknownPriorityException | |
| 23 | */ | |
| 24 | #[\Override] | |
| 25 | public function emit(MessageInterface $message, int $priority = Dispatcher::DEFAULT_PRIORITY): EmitterInterface | |
| 26 | { | |
| 27 | $this->driver->send($message, $priority); | |
| 28 | ||
| 29 | $this->log( | |
| 30 | LogLevel::INFO, | |
| 31 | "Emitter send message #{$message->getId()} to driver " . $this->driver::class, | |
| 32 | $this->messageLoggerContext($message), | |
| 33 | ); | |
| 34 | return $this; | |
| 35 | } | |
| 36 | ||
| 37 | /** | |
| 38 | * Serialize message to logger context | |
| 39 | * | |
| 40 | * @return array<string, mixed> | |
| 41 | */ | |
| 42 | private function messageLoggerContext(MessageInterface $message): array | |
| 43 | { | |
| 44 | return [ | |
| 45 | 'id' => $message->getId(), | |
| 46 | 'created' => $message->getCreated(), | |
| 47 | 'type' => $message->getType(), | |
| 48 | 'payload' => $message->getPayload(), | |
| 49 | ]; | |
| 50 | } | |
| 51 | ||
| 52 | /** | |
| 53 | * Internal log method wrapper | |
| 54 | * | |
| 55 | * @param array<mixed> $context | |
| 56 | */ | |
| 57 | private function log(string $level, string $message, array $context = []): void | |
| 58 | { | |
| 59 | if ($this->logger instanceof LoggerInterface) { | |
| 60 | $this->logger->log($level, $message, $context); | |
| 61 | } | |
| 62 | } | |
| 63 | } |