|
5 | 5 | namespace Yiisoft\Queue\Message; |
6 | 6 |
|
7 | 7 | /** |
8 | | - * ID envelope allows identifying a message. |
| 8 | + * ID envelope allows to identify a message. |
9 | 9 | */ |
10 | | -final class IdEnvelope implements EnvelopeInterface |
| 10 | +final class IdEnvelope extends Envelope |
11 | 11 | { |
12 | | - use EnvelopeTrait; |
13 | | - |
14 | 12 | public const MESSAGE_ID_KEY = 'yii-message-id'; |
15 | 13 |
|
16 | 14 | public function __construct( |
17 | | - MessageInterface $message, |
18 | | - private readonly string|int|null $id = null, |
| 15 | + protected MessageInterface $message, |
| 16 | + private readonly string|int|null $id, |
19 | 17 | ) { |
20 | | - $this->message = $message; |
21 | 18 | } |
22 | 19 |
|
23 | | - public static function fromMessage(MessageInterface $message): self |
| 20 | + public static function fromMessage(MessageInterface $message): static |
24 | 21 | { |
25 | | - return new self($message, self::getIdFromMessage($message)); |
| 22 | + /** @var mixed $rawId */ |
| 23 | + $rawId = $message->getMetadata()[self::MESSAGE_ID_KEY] ?? null; |
| 24 | + |
| 25 | + /** @var int|string|null $id */ |
| 26 | + $id = match (true) { |
| 27 | + $rawId === null => null, // don't remove this branch: it's important for compute speed |
| 28 | + is_string($rawId) => $rawId, |
| 29 | + is_int($rawId) => $rawId, |
| 30 | + is_object($rawId) && method_exists($rawId, '__toString') => (string)$rawId, |
| 31 | + default => null, |
| 32 | + }; |
| 33 | + |
| 34 | + return new self($message, $id); |
26 | 35 | } |
27 | 36 |
|
28 | 37 | public function getId(): string|int|null |
29 | 38 | { |
30 | | - return $this->id ?? self::getIdFromMessage($this->message); |
| 39 | + return $this->id; |
31 | 40 | } |
32 | 41 |
|
33 | | - private function getEnvelopeMetadata(): array |
| 42 | + protected function getEnvelopeMetadata(): array |
34 | 43 | { |
35 | 44 | return [self::MESSAGE_ID_KEY => $this->getId()]; |
36 | 45 | } |
37 | | - |
38 | | - private static function getIdFromMessage(MessageInterface $message): string|int|null |
39 | | - { |
40 | | - $id = $message->getMetadata()[self::MESSAGE_ID_KEY] ?? null; |
41 | | - if ($id instanceof \Stringable) { |
42 | | - $id = (string) $id; |
43 | | - } |
44 | | - |
45 | | - // We don't throw an error as this value could come from external sources, |
46 | | - // and we should process the message either way |
47 | | - if (!is_string($id) && !is_int($id)) { |
48 | | - return null; |
49 | | - } |
50 | | - |
51 | | - return $id; |
52 | | - } |
53 | 46 | } |
0 commit comments