Lines 0.00% 0 / 14
Functions and Methods 0.00% 0 / 4
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
FakeWebsocketConnector 0.00% 0 / 14 0.00% 0 / 4 30 0.00% 0 / 1
 __construct 0.00% 0 / 2 0.00% 0 / 1 2
 createStalled 0.00% 0 / 3 0.00% 0 / 1 2
 createAuthenticatedConnection 0.00% 0 / 4 0.00% 0 / 1 2
 connect 0.00% 0 / 5 0.00% 0 / 1 6
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Testing\Websocket;
6
7use Amp\Cancellation;
8use Amp\DeferredFuture;
9use Amp\Websocket\Client\WebsocketConnection;
10use Amp\Websocket\Client\WebsocketConnector;
11use Amp\Websocket\Client\WebsocketHandshake;
12use LogicException;
13use Stewart\Testing\Websocket\Collection\FakeWebsocketConnectionCollection;
14
15final class FakeWebsocketConnector implements WebsocketConnector
16{
17    public private(set) FakeWebsocketConnectionCollection $connections;
18
19    /** @var list<FakeWebsocketConnection> */
20    private array $sockets;
21
22    private bool $stalls = false;
23
24    public function __construct(FakeWebsocketConnection ...$sockets)
25    {
26        $this->sockets = array_values($sockets);
27        $this->connections = FakeWebsocketConnectionCollection::empty();
28    }
29
30    public static function createStalled(): self
31    {
32        $connector = new self();
33        $connector->stalls = true;
34
35        return $connector;
36    }
37
38    public static function createAuthenticatedConnection(string $haVersion = '2026.9.0'): FakeWebsocketConnection
39    {
40        $socket = new FakeWebsocketConnection();
41        $socket->queueFrame(['type' => 'auth_required', 'ha_version' => $haVersion]);
42        $socket->replyWhenSent('auth', ['type' => 'auth_ok', 'ha_version' => $haVersion]);
43
44        return $socket;
45    }
46
47    public function connect(WebsocketHandshake $handshake, ?Cancellation $cancellation = null): WebsocketConnection
48    {
49        if ($this->stalls) {
50            new DeferredFuture()->getFuture()->await($cancellation);
51        }
52
53        $socket = array_shift($this->sockets) ?? throw new LogicException('The fake connector ran out of sockets.');
54        $this->connections = $this->connections->withConnection($socket);
55
56        return $socket;
57    }
58}