Lines 100.00% 32 / 32
Functions and Methods 100.00% 9 / 9
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
Connection 100.00% 32 / 32 100.00% 9 / 9 13 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 open 100.00% 1 / 1 100.00% 1 / 1 1
 server 100.00% 1 / 1 100.00% 1 / 1 1
 send 100.00% 10 / 10 100.00% 1 / 1 3
 receive 100.00% 13 / 13 100.00% 1 / 1 3
 traffic 100.00% 1 / 1 100.00% 1 / 1 1
 witnessed 100.00% 2 / 2 100.00% 1 / 1 1
 close 100.00% 2 / 2 100.00% 1 / 1 1
 closedHere 100.00% 1 / 1 100.00% 1 / 1 1
1<?php
2
3declare(strict_types=1);
4
5namespace Lorekeeper\Client;
6
7use Lorekeeper\Client\Command\Command;
8use Lorekeeper\Server\Message\Message;
9use Lorekeeper\Server\Server;
10use Psl\Async\CancellationTokenInterface;
11use Psl\Async\NullCancellationToken;
12use Psl\IO;
13use Psl\Observer\SubjectInterface;
14use Psl\Option;
15use Psl\TCP;
16
17final class Connection implements SubjectInterface
18{
19    use Observable;
20
21    private const string TERMINATOR = "\0";
22
23    private readonly IO\Reader $reader;
24
25    private ?string $closedBecause = null;
26
27    private bool $closedHere = false;
28
29    private ?Traffic $traffic = null;
30
31    public function __construct(
32        private readonly TCP\StreamInterface $stream,
33        private readonly ?Server $server = null,
34    ) {
35        $this->reader = new IO\Reader($stream);
36    }
37
38    public static function open(Server $server): self
39    {
40        return new self(TCP\connect($server->address->host, $server->address->port ?? 0), $server);
41    }
42
43    public function server(): ?Server
44    {
45        return $this->server;
46    }
47
48    /** @throws PeerClosedException */
49    public function send(Command $command): void
50    {
51        if ($this->closedBecause !== null) {
52            throw new PeerClosedException($this->closedBecause);
53        }
54
55        $message = $command->toMessage();
56        try {
57            $this->stream->writeAll($message . self::TERMINATOR);
58        } catch (IO\Exception\RuntimeException $exception) {
59            throw new PeerClosedException(
60                'Connection error while sending: ' . $exception->getMessage(),
61                previous: $exception,
62            );
63        }
64
65        $this->witnessed(TrafficDirection::Sent, $message);
66    }
67
68    /**
69     * @throws PeerClosedException
70     *
71     * @return Option\Option<Message>
72     */
73    public function receive(CancellationTokenInterface $cancellation = new NullCancellationToken()): Option\Option
74    {
75        try {
76            $raw = $this->reader->readUntil(self::TERMINATOR, $cancellation);
77        } catch (IO\Exception\RuntimeException $exception) {
78            $this->closedBecause = 'Connection error while receiving: ' . $exception->getMessage();
79
80            throw new PeerClosedException($this->closedBecause, previous: $exception);
81        }
82
83        if ($raw === null) {
84            $this->closedBecause = 'The server closed the connection.';
85
86            throw new PeerClosedException($this->closedBecause);
87        }
88
89        $message = MessageParser::parse($raw);
90        $this->witnessed(
91            TrafficDirection::Received,
92            $message->map(static fn(Message $parsed): string => $parsed->raw)->unwrapOr($raw),
93        );
94
95        return $message;
96    }
97
98    public function traffic(): ?Traffic
99    {
100        return $this->traffic;
101    }
102
103    private function witnessed(TrafficDirection $direction, string $message): void
104    {
105        $this->traffic = new Traffic($direction, $message);
106        $this->notify();
107    }
108
109    public function close(): void
110    {
111        $this->closedHere = true;
112        $this->stream->close();
113    }
114
115    public function closedHere(): bool
116    {
117        return $this->closedHere;
118    }
119}