Lines 100.00% 13 / 13
Functions and Methods 100.00% 2 / 2
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
TopicPayload 100.00% 13 / 13 100.00% 2 / 2 10 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 assertTransportable 100.00% 12 / 12 100.00% 1 / 1 9
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Support\Wire;
6
7use Stewart\Contracts\Exception\TopicError;
8use Stewart\Contracts\Exception\TopicException;
9
10/** @internal */
11final readonly class TopicPayload
12{
13    /**
14     * @param array<mixed>|bool|float|int|string|null $value
15     * @throws TopicException
16     */
17    public function __construct(public bool|int|float|string|array|null $value)
18    {
19        $this->assertTransportable($value, 'payload');
20    }
21
22    /** @throws TopicException */
23    private function assertTransportable(mixed $value, string $path): void
24    {
25        if (\is_float($value) && !is_finite($value)) {
26            throw TopicException::createForReason(
27                TopicError::PayloadInvalid,
28                path: $path,
29                actualType: \sprintf('float(%s)', is_nan($value) ? 'NAN' : ($value > 0 ? 'INF' : '-INF')),
30            );
31        }
32
33        if ($value === null || \is_scalar($value)) {
34            return;
35        }
36
37        if (!\is_array($value)) {
38            throw TopicException::createForReason(TopicError::PayloadInvalid, path: $path, actualType: get_debug_type($value));
39        }
40
41        foreach ($value as $key => $item) {
42            $this->assertTransportable($item, $path . '[' . $key . ']');
43        }
44    }
45}