Lines 42.62% 26 / 61
Methods 20.68% 6 / 29
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 queueFrame 100.00% 2 / 2 100.00% 1 / 1 1
 queueCoalescedFrame 100.00% 2 / 2 100.00% 1 / 1 1
 replyWhenSent 100.00% 1 / 1 100.00% 1 / 1 1
 answerEverySend 100.00% 1 / 1 100.00% 1 / 1 1
 holdSendsUntil 0.00% 0 / 1 0.00% 0 / 1 2
 holdCloseUntil 0.00% 0 / 1 0.00% 0 / 1 2
 listSentOfType 0.00% 0 / 1 0.00% 0 / 1 2
 receive 28.57% 2 / 7 0.00% 0 / 1 6.28
 sendText 92.85% 13 / 14 0.00% 0 / 1 8.02
 close 0.00% 0 / 8 0.00% 0 / 1 12
 isClosed 0.00% 0 / 1 0.00% 0 / 1 2
 getCloseInfo 0.00% 0 / 1 0.00% 0 / 1 2
 onClose 0.00% 0 / 1 0.00% 0 / 1 2
 getId 0.00% 0 / 1 0.00% 0 / 1 2
 getLocalAddress 0.00% 0 / 1 0.00% 0 / 1 2
 getRemoteAddress 0.00% 0 / 1 0.00% 0 / 1 2
 getTlsInfo 0.00% 0 / 1 0.00% 0 / 1 2
 isCompressionEnabled 0.00% 0 / 1 0.00% 0 / 1 2
 sendBinary 0.00% 0 / 1 0.00% 0 / 1 2
 streamText 0.00% 0 / 1 0.00% 0 / 1 2
 streamBinary 0.00% 0 / 1 0.00% 0 / 1 2
 ping 0.00% 0 / 1 0.00% 0 / 1 2
 getCount 0.00% 0 / 1 0.00% 0 / 1 2
 getTimestamp 0.00% 0 / 1 0.00% 0 / 1 2
 getHandshakeResponse 0.00% 0 / 1 0.00% 0 / 1 2
 getIterator 0.00% 0 / 2 0.00% 0 / 1 6
 encodeFrame 100.00% 1 / 1 100.00% 1 / 1 1
 wakeReceiver 75.00% 3 / 4 0.00% 0 / 1 2.06
28final class FakeWebsocketConnection implements IteratorAggregate, WebsocketConnection
29{
30    /** @var list<array<string, mixed>> */
31    public array $sent = [];
32
33    /** @var SplQueue<string> */
34    private SplQueue $inbound;
35
36    /** @var list<DeferredFuture<null>> */
37    private array $waiting = [];
38
39    /** @var array<string, list<array<string, mixed>>> */
40    private array $onSend = [];
41
42    /** @var array<string, Closure(array<string, mixed>): ?array<string, mixed>> */
43    private array $answerers = [];
44
45    private bool $closed = false;
46
47    private ?WebsocketCloseInfo $closeInfo = null;
48
49    /** @var list<Closure(int, WebsocketCloseInfo): void> */
50    private array $onClose = [];
51
52    private ?Latch $sendRelease = null;
53
54    private ?Latch $closeRelease = null;
55
56    public function __construct()
57    {
58        $this->inbound = new SplQueue();
59    }
60
61    /** @param array<string, mixed> $frame */
62    public function queueFrame(array $frame): void
63    {
64        $this->inbound->enqueue(self::encodeFrame($frame));
65        $this->wakeReceiver();
66    }
67
68    /** @param array<string, mixed> ...$frames */
69    public function queueCoalescedFrame(array ...$frames): void
70    {
71        $this->inbound->enqueue(self::encodeFrame(array_values($frames)));
72        $this->wakeReceiver();
73    }
74
75    /** @param array<string, mixed> $frame */
76    public function replyWhenSent(string $type, array $frame): void
77    {
78        $this->onSend[$type][] = $frame;
79    }
80
81    // The answer may be null to reply later through queueFrame().
82    /** @param Closure(array<string, mixed>): ?array<string, mixed> $answer */
83    public function answerEverySend(string $type, Closure $answer): void
84    {
85        $this->answerers[$type] = $answer;
86    }
87
88    public function holdSendsUntil(Latch $release): void
89    {
90        $this->sendRelease = $release;
91    }
92
93    public function holdCloseUntil(Latch $release): void
94    {
95        $this->closeRelease = $release;
96    }
97
98    /** @return list<array<string, mixed>> */
99    public function listSentOfType(string $type): array
100    {
101        return array_values(array_filter($this->sent, static fn(array $command): bool => ($command['type'] ?? null) === $type));
102    }
103
104    public function receive(?Cancellation $cancellation = null): ?WebsocketMessage
105    {
106        while ($this->inbound->isEmpty()) {
107            if ($this->closed) {
108                return null;
109            }
110
111            /** @var DeferredFuture<null> $deferred */
112            $deferred = new DeferredFuture();
113            $this->waiting[] = $deferred;
114            $deferred->getFuture()->await($cancellation);
115        }
116
117        return WebsocketMessage::fromText($this->inbound->dequeue());
118    }
119
120    public function sendText(string $data): void
121    {
122        $this->sendRelease?->waitUntilOpen();
123
124        if ($this->closed) {
125            throw new LogicException('The fake socket is closed.');
126        }
127
128        /** @var array<string, mixed> $command */
129        $command = json_decode($data, true, 512, \JSON_THROW_ON_ERROR);
130        $this->sent[] = $command;
131
132        $type = \is_string($command['type'] ?? null) ? $command['type'] : '';
133        $id = $command['id'] ?? null;
134
135        $frames = $this->onSend[$type] ?? [];
136        unset($this->onSend[$type]);
137
138        $answer = $frames === [] && isset($this->answerers[$type]) ? ($this->answerers[$type])($command) : null;
139
140        if ($answer !== null) {
141            $frames = [$answer];
142        }
143
144        foreach ($frames as $frame) {
145            $this->queueFrame(\is_int($id) ? ['id' => $id, ...$frame] : $frame);
146        }
147    }
148
149    public function close(int $code = WebsocketCloseCode::NORMAL_CLOSE, string $reason = ''): void
150    {
151        if ($this->closed) {
152            return;
153        }
154
155        $this->closed = true;
156        $closeInfo = $this->closeInfo = new WebsocketCloseInfo($code, $reason, microtime(true), false);
157        $this->wakeReceiver();
158        $this->closeRelease?->waitUntilOpen();
159
160        foreach ($this->onClose as $handler) {
161            $handler($this->getId(), $closeInfo);
162        }
163    }
164
165    public function isClosed(): bool
166    {
167        return $this->closed;
168    }
169
170    public function getCloseInfo(): WebsocketCloseInfo
171    {
172        return $this->closeInfo ??= new WebsocketCloseInfo(WebsocketCloseCode::NORMAL_CLOSE, '', microtime(true), false);
173    }
174
175    public function onClose(Closure $onClose): void
176    {
177        $this->onClose[] = $onClose;
178    }
179
180    public function getId(): int
181    {
182        return 1;
183    }
184
185    public function getLocalAddress(): SocketAddress
186    {
187        return new InternetAddress('127.0.0.1', 1234);
188    }
189
190    public function getRemoteAddress(): SocketAddress
191    {
192        return new InternetAddress('127.0.0.1', 8123);
193    }
194
195    public function getTlsInfo(): ?TlsInfo
196    {
197        return null;
198    }
199
200    public function isCompressionEnabled(): bool
201    {
202        return false;
203    }
204
205    public function sendBinary(string $data): void
206    {
207        throw new LogicException('Stewart never sends binary frames.');
208    }
209
210    public function streamText(ReadableStream $stream): void
211    {
212        throw new LogicException('Stewart never streams frames.');
213    }
214
215    public function streamBinary(ReadableStream $stream): void
216    {
217        throw new LogicException('Stewart never streams frames.');
218    }
219
220    public function ping(): void {}
221
222    public function getCount(WebsocketCount $type): int
223    {
224        return 0;
225    }
226
227    public function getTimestamp(WebsocketTimestamp $type): float
228    {
229        return microtime(true);
230    }
231
232    public function getHandshakeResponse(): Response
233    {
234        throw new LogicException('The fake socket has no handshake response.');
235    }
236
237    public function getIterator(): Traversable
238    {
239        while (($message = $this->receive()) !== null) {
240            yield $message;
241        }
242    }
243
244    /** @param array<array-key, mixed> $frame */
245    private static function encodeFrame(array $frame): string
246    {
247        return json_encode($frame, \JSON_THROW_ON_ERROR);
248    }
249
250    private function wakeReceiver(): void
251    {
252        $waiting = $this->waiting;
253        $this->waiting = [];
254
255        foreach ($waiting as $deferred) {
256            $deferred->complete();
257        }
258    }
259}