-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMessageContext.php
87 lines (75 loc) · 2.33 KB
/
MessageContext.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
declare(strict_types=1);
namespace Telephantast\MessageBus;
use Telephantast\Message\Message;
/**
* @api
* @template TResult
* @template TMessage of Message<TResult>
* @extends ReadonlyMessageContext<TResult, TMessage>
*/
final class MessageContext extends ReadonlyMessageContext
{
/**
* @param Envelope<TResult, TMessage> $envelope
*/
protected function __construct(
private readonly MessageBus $messageBus,
Envelope $envelope,
?ReadonlyMessageContext $parent = null,
) {
parent::__construct($envelope, $parent);
}
/**
* @internal
* @psalm-internal Telephantast\MessageBus
* @template TTResult
* @template TTMessage of Message<TTResult>
* @param TTMessage|Envelope<TTResult, TTMessage> $messageOrEnvelope
* @return self<TTResult, TTMessage>
*/
public static function start(MessageBus $messageBus, Envelope|Message $messageOrEnvelope): self
{
return new self($messageBus, Envelope::wrap($messageOrEnvelope));
}
public function setAttribute(ContextAttribute ...$attributes): void
{
foreach ($attributes as $attribute) {
$this->attributes[$attribute::class] = $attribute;
}
}
/**
* @param TMessage $message
*/
public function setMessage(Message $message): void
{
$this->envelope = $this->envelope->withMessage($message);
}
public function setStamp(Stamp ...$stamps): void
{
$this->envelope = $this->envelope->withStamp(...$stamps);
}
/**
* @param class-string<Stamp> ...$classes
*/
public function removeStamp(string ...$classes): void
{
$this->envelope = $this->envelope->withoutStamp(...$classes);
}
/**
* @template TTResult
* @template TTMessage of Message<TTResult>
* @param TTMessage|Envelope<TTResult, TTMessage> $messageOrEnvelope
* @return TTResult
*/
public function dispatch(Envelope|Message $messageOrEnvelope): mixed
{
$child = new self($this->messageBus, Envelope::wrap($messageOrEnvelope), clone $this);
foreach ($this->attributes as $attribute) {
if ($attribute instanceof InheritableContextAttribute) {
$child->setAttribute($attribute);
}
}
return $this->messageBus->handleContext($child);
}
}