• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

basis-company / nats.php / 44931272822

21 Nov 2026 05:34PM UTC coverage: 95.514% (+0.01%) from 95.504%
44931272822

push

github

nekufa
Fix testInvalidConnection to accept PHP DSN port parse error

Newer PHP versions fail stream_socket_client("host:-1") while parsing
the DSN instead of reaching the socket layer, so the expected error is
"Failed to parse port of address" rather than a platform-specific
connection error.

1597 of 1672 relevant lines covered (95.51%)

140.51 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

94.3
/src/Client.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace Basis\Nats;
6

7
use Basis\Nats\Message\Msg;
8
use Basis\Nats\Message\Payload;
9
use Basis\Nats\Message\Publish;
10
use Basis\Nats\Message\Subscribe;
11
use Basis\Nats\Message\Unsubscribe;
12
use Basis\Nats\Service\Service;
13
use Exception;
14
use LogicException;
15
use Psr\Log\LoggerInterface;
16

17
class Client
18
{
19
    public readonly Api $api;
20

21
    private string $name = '';
22

23
    /** @var array<callable|Queue> */
24
    private array $handlers = [];
25
    private array $subscriptions = [];
26

27
    private array $services = [];
28

29
    private bool $skipInvalidMessages = false;
30

31
    private string $requestsSubject = '';
32

33
    private bool $requestsSubscribed = false;
34

35
    private int $nextRid = 0;
36

37
    private string $requestsSid = '';
38

39
    public function __construct(
600 ✔
40
        public readonly Configuration $configuration = new Configuration(),
41
        public ?LoggerInterface $logger = null,
42
        public ?Connection $connection = null,
43
    ) {
44
        $this->api = new Api($this);
600 ✔
45
        if (!$connection) {
600 ✔
46
            $this->connection = new Connection(client: $this, logger: $logger);
600 ✔
47
        }
48

49
        $this->requestsSubject = '_REQS.' . bin2hex(random_bytes(16));
600 ✔
50
        $this->requestsSid = '_REQS.' . $this->getnextRid();
600 ✔
51
    }
52

53
    public function api($command, array $args = [], ?callable $callback = null): ?object
592 ✔
54
    {
55
        $subject = "\$JS.API.$command";
592 ✔
56
        $options = json_encode((object)$args);
592 ✔
57

58
        if ($callback) {
592 ✔
59
            return $this->request($subject, $options, $callback);
×
60
        }
61

62
        $result = $this->dispatch($subject, $options);
592 ✔
63

64
        if ($result->error ?? false) {
592 ✔
65
            throw new Exception($result->error->description, $result->error->err_code);
4 ✔
66
        }
67

68
        if (!$result) {
592 ✔
69
            return null;
×
70
        }
71

72
        return $result;
592 ✔
73
    }
74

75
    public function dispatch(string $name, mixed $payload, ?float $timeout = null)
592 ✔
76
    {
77
        if ($timeout === null) {
592 ✔
78
            $timeout = $this->configuration->timeout;
592 ✔
79
        }
80

81
        $context = (object)[
592 ✔
82
            'processed' => false,
592 ✔
83
            'result' => null,
592 ✔
84
            'threshold' => microtime(true) + $timeout,
592 ✔
85
        ];
592 ✔
86

87
        $this->request($name, $payload, function ($result) use ($context) {
592 ✔
88
            $context->processed = true;
592 ✔
89
            $context->result = $result;
592 ✔
90
        });
592 ✔
91

92
        while (!$context->processed && microtime(true) < $context->threshold) {
592 ✔
93
            $this->process();
8 ✔
94
        }
95

96
        if (!$context->processed) {
592 ✔
97
            throw new LogicException("Processing timeout");
×
98
        }
99

100
        return $context->result;
592 ✔
101
    }
102

103
    public function getApi(): Api
592 ✔
104
    {
105
        return $this->api;
592 ✔
106
    }
107

108
    public function ping(): bool
76 ✔
109
    {
110
        return $this->connection->ping();
76 ✔
111
    }
112

113
    public function publish(string $name, mixed $payload, ?string $replyTo = null): self
592 ✔
114
    {
115
        $this->connection->sendMessage(new Publish([
592 ✔
116
            'payload' => Payload::parse($payload),
592 ✔
117
            'replyTo' => $replyTo,
592 ✔
118
            'subject' => $name,
592 ✔
119
        ]));
592 ✔
120

121
        return $this;
592 ✔
122
    }
123

124
    public function request(string $name, mixed $payload, callable $handler): self
592 ✔
125
    {
126
        $this->subscribeRequests();
592 ✔
127

128
        $replyTo = $this->getNextReplyTo();
592 ✔
129

130
        $this->handlers[$replyTo] = $handler;
592 ✔
131

132
        $this->publish($name, $payload, $replyTo);
592 ✔
133
        $this->process($this->configuration->timeout);
592 ✔
134

135
        return $this;
592 ✔
136
    }
137

138
    public function subscribe(string $name, ?callable $handler = null): self|Queue
160 ✔
139
    {
140
        return $this->doSubscribe($name, null, $handler);
160 ✔
141
    }
142

143
    public function subscribeQueue(string $name, string $group, ?callable $handler = null): self|Queue
52 ✔
144
    {
145
        return $this->doSubscribe($name, $group, $handler);
52 ✔
146
    }
147

148
    public function unsubscribe(string|Queue $name): self
52 ✔
149
    {
150
        if ($name instanceof Queue) {
52 ✔
151
            $name = $name->subject;
48 ✔
152
        }
153
        foreach ($this->subscriptions as $i => $subscription) {
52 ✔
154
            if ($subscription['name'] === $name) {
52 ✔
155
                unset($this->subscriptions[$i]);
52 ✔
156
                $this->connection->sendMessage(new Unsubscribe(['sid' => $subscription['sid']]));
52 ✔
157
                unset($this->handlers[$subscription['sid']]);
52 ✔
158
            }
159
        }
160

161
        return $this;
52 ✔
162
    }
163

164
    public function getSubscriptions(): array
32 ✔
165
    {
166
        return $this->subscriptions;
32 ✔
167
    }
168

169
    public function setDelay(float $delay, string $mode = Configuration::DELAY_CONSTANT): self
8 ✔
170
    {
171
        $this->configuration->setDelay($delay, $mode);
8 ✔
172
        return $this;
8 ✔
173
    }
174

175
    public function setLogger(?LoggerInterface $logger): self
4 ✔
176
    {
177
        $this->logger = $logger;
4 ✔
178
        return $this;
4 ✔
179
    }
180

181
    public function process(null|int|float $timeout = 0, bool $reply = true): mixed
592 ✔
182
    {
183
        $message = $this->connection->getMessage($timeout);
592 ✔
184

185
        if ($message instanceof Msg) {
592 ✔
186
            if (array_key_exists($message->subject, $this->handlers)) {
592 ✔
187
                $result = $this->processMsg($this->handlers[$message->subject], $message, $reply);
592 ✔
188
                unset($this->handlers[$message->subject]);
592 ✔
189
                return $result;
592 ✔
190
            }
191
            if (array_key_exists($message->sid, $this->handlers)) {
120 ✔
192
                return $this->processMsg($this->handlers[$message->sid], $message, $reply);
120 ✔
193
            }
194
            if ($this->skipInvalidMessages) {
×
195
                return null;
×
196
            }
197
            throw new LogicException("No handler for message $message->sid or $message->subject");
×
198
        } else {
199
            return $message;
65 ✔
200
        }
201
    }
202

203
    private function doSubscribe(string $subject, ?string $group, ?callable $handler = null): self|Queue
168 ✔
204
    {
205
        $sid = bin2hex(random_bytes(4));
168 ✔
206
        if ($handler === null) {
168 ✔
207
            $this->handlers[$sid] = new Queue($this, $subject);
80 ✔
208
        } else {
209
            $this->handlers[$sid] = $handler;
88 ✔
210
        }
211

212
        $this->connection->sendMessage(new Subscribe([
168 ✔
213
            'sid' => $sid,
168 ✔
214
            'subject' => $subject,
168 ✔
215
            'group' => $group,
168 ✔
216
        ]));
168 ✔
217

218
        $this->subscriptions[] = [
168 ✔
219
            'name' => $subject,
168 ✔
220
            'sid' => $sid,
168 ✔
221
            'group' => $group,
168 ✔
222
        ];
168 ✔
223

224
        if ($handler === null) {
168 ✔
225
            return $this->handlers[$sid];
80 ✔
226
        }
227
        return $this;
88 ✔
228
    }
229

230
    public function getName(): string
592 ✔
231
    {
232
        return $this->name;
592 ✔
233
    }
234

235
    public function setName(string $name): self
4 ✔
236
    {
237
        $this->name = $name;
4 ✔
238
        return $this;
4 ✔
239
    }
240

241
    public function setTimeout(float $value): self
×
242
    {
243
        $this->connection->setTimeout($value);
×
244
        return $this;
×
245
    }
246

247
    public function skipInvalidMessages(bool $skipInvalidMessages): self
24 ✔
248
    {
249
        $this->skipInvalidMessages = $skipInvalidMessages;
24 ✔
250
        return $this;
24 ✔
251
    }
252

253
    public function unsubscribeAll(): self
592 ✔
254
    {
255
        $this->unsubscribeRequests();
592 ✔
256

257
        foreach ($this->subscriptions as $index => $subscription) {
592 ✔
258
            unset($this->subscriptions[$index]);
12 ✔
259
            $this->connection->sendMessage(new Unsubscribe(['sid' => $subscription['sid']]));
12 ✔
260
            unset($this->handlers[$subscription['sid']]);
12 ✔
261
        }
262

263
        return $this;
592 ✔
264
    }
265

266
    public function disconnect(): self
592 ✔
267
    {
268
        if ($this->connection) {
592 ✔
269
            $this->unsubscribeAll();
592 ✔
270
            $this->connection->close();
592 ✔
271
            $this->connection = null;
592 ✔
272
        }
273
        return $this;
592 ✔
274
    }
275

276
    public function service(string $name, string $description, string $version): Service
44 ✔
277
    {
278
        if (!array_key_exists($name, $this->services)) {
44 ✔
279
            $this->services[$name] = new Service($this, $name, $description, $version);
44 ✔
280
        }
281

282
        return $this->services[$name];
44 ✔
283
    }
284

285
    private function getNextRid(): string
600 ✔
286
    {
287
        $this->nextRid++;
600 ✔
288

289
        return (string)$this->nextRid;
600 ✔
290
    }
291

292
    private function getNextReplyTo(): string
592 ✔
293
    {
294
        return $this->requestsSubject . '.' . $this->getNextRid();
592 ✔
295
    }
296

297
    public function subscribeRequests(bool $force = false): void
592 ✔
298
    {
299
        if (!$this->requestsSubscribed || $force) {
592 ✔
300
            $this->connection->sendMessage(new Subscribe([
592 ✔
301
                'sid' => $this->requestsSid,
592 ✔
302
                'subject' => $this->requestsSubject . '.' . '*',
592 ✔
303
            ]));
592 ✔
304

305
            $this->requestsSubscribed = true;
592 ✔
306
        }
307
    }
308

309
    private function unsubscribeRequests(): void
592 ✔
310
    {
311
        if (!$this->requestsSubscribed) {
592 ✔
312
            $this->connection->sendMessage(new Unsubscribe(['sid' => (string)$this->requestsSid]));
8 ✔
313
            $this->requestsSubscribed = true;
8 ✔
314
        }
315
    }
316

317
    public function requestsSubscribed(): bool
28 ✔
318
    {
319
        return $this->requestsSubscribed;
28 ✔
320
    }
321

322
    private function processMsg($handler, Msg $message, bool $reply): mixed
592 ✔
323
    {
324
        if ($handler instanceof Queue) {
592 ✔
325
            $handler->handle($message);
64 ✔
326
            return $handler;
64 ✔
327
        } else {
328
            $result = $handler($message->payload, $message->replyTo);
592 ✔
329
            if ($reply && $message->replyTo) {
592 ✔
330
                $message->reply($result);
12 ✔
331
            }
332
            return $result;
592 ✔
333
        }
334
    }
335
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc