Lines 98.16% 107 / 109
Methods 91.66% 22 / 24
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 encodeObject 100.00% 13 / 13 100.00% 1 / 1 5
 encodeObjectList 100.00% 1 / 1 100.00% 1 / 1 1
 normalizeObject 100.00% 2 / 2 100.00% 1 / 1 2
 decodeObject 100.00% 6 / 6 100.00% 1 / 1 2
 decodeFields 100.00% 10 / 10 100.00% 1 / 1 7
 decodeObjectList 100.00% 3 / 3 100.00% 1 / 1 2
 normalizeFields 100.00% 5 / 5 100.00% 1 / 1 5
 normalizeValue 90.00% 9 / 10 0.00% 0 / 1 9.08
 normalizeEnum 100.00% 2 / 2 100.00% 1 / 1 1
 normalizeNestedObject 100.00% 2 / 2 100.00% 1 / 1 1
 normalizeVariant 100.00% 4 / 4 100.00% 1 / 1 3
 normalizeConvertedValue 100.00% 2 / 2 100.00% 1 / 1 2
 normalizeListItems 100.00% 3 / 3 100.00% 1 / 1 3
 normalizeMap 100.00% 2 / 2 100.00% 1 / 1 2
 decodeValue 100.00% 14 / 14 100.00% 1 / 1 22
 decodeNestedObject 100.00% 2 / 2 100.00% 1 / 1 2
 decodeVariant 88.88% 8 / 9 0.00% 0 / 1 4.02
 decodeConvertedValue 100.00% 2 / 2 100.00% 1 / 1 1
 decodeFragment 100.00% 2 / 2 100.00% 1 / 1 1
 decodeListItems 100.00% 7 / 7 100.00% 1 / 1 4
 decodeEnum 100.00% 5 / 5 100.00% 1 / 1 4
 describeEnumCases 100.00% 1 / 1 100.00% 1 / 1 1
 createWrongTypeException 100.00% 1 / 1 100.00% 1 / 1 1
17final class WireMapper
18{
19    public function __construct(public readonly ClassShapeReader $shapes) {}
20
21    /** @throws JsonException|StewartException */
22    public function encodeObject(object $dto): string
23    {
24        $converter = $this->shapes->findConverterForClass($dto::class);
25
26        if ($converter !== null) {
27            return JsonEncoder::encodeToJson($converter->encodeValue($dto));
28        }
29
30        $shape = $this->shapes->resolveClassShape($dto::class);
31
32        if (!$shape->holdsFragment) {
33            return JsonEncoder::encodeToJson($this->normalizeFields($shape, $dto));
34        }
35
36        $members = [];
37
38        foreach ($shape->fields as $field) {
39            $value = $dto->{$field->property};
40            $members[] = JsonEncoder::encodeToJson($field->key) . ':' . ($value instanceof JsonFragment
41                ? $value->encodeToJson($this)
42                : JsonEncoder::encodeToJson($this->normalizeValue($field->value, $value)));
43        }
44
45        return '{' . implode(',', $members) . '}';
46    }
47
48    /**
49     * @param list<object> $dtos
50     * @throws JsonException|StewartException
51     */
52    public function encodeObjectList(array $dtos): string
53    {
54        return JsonEncoder::encodeToJson(array_map($this->normalizeObject(...), $dtos));
55    }
56
57    /** @throws StewartException */
58    public function normalizeObject(object $dto): mixed
59    {
60        $converter = $this->shapes->findConverterForClass($dto::class);
61
62        return $converter === null ? $this->normalizeFields($this->shapes->resolveClassShape($dto::class), $dto) : $converter->encodeValue($dto);
63    }
64
65    /**
66     * @template T of object
67     * @param class-string<T> $class
68     * @param array<array-key, mixed> $data
69     * @return T
70     * @throws StewartException
71     */
72    public function decodeObject(string $class, array $data, string $path = ''): object
73    {
74        $converter = $this->shapes->findConverterForClass($class);
75
76        if ($converter === null) {
77            return $this->decodeFields($class, $data, $path);
78        }
79
80        $decoded = $converter->decodeValue($data, $path);
81        \assert($decoded instanceof $class);
82
83        return $decoded;
84    }
85
86    /**
87     * @template T of object
88     * @param class-string<T> $class
89     * @param array<array-key, mixed> $data
90     * @return T
91     * @throws StewartException
92     */
93    private function decodeFields(string $class, array $data, string $path): object
94    {
95        $arguments = [];
96
97        foreach ($this->shapes->resolveClassShape($class)->fields as $field) {
98            $fieldPath = $path === '' ? $field->key : $path . '.' . $field->key;
99
100            if (!\array_key_exists($field->key, $data)) {
101                throw JsonShapeException::missing($fieldPath, $field->value->describeExpectedValue());
102            }
103
104            $value = $data[$field->key];
105            $arguments[] = $value === null && $field->nullable ? null : $this->decodeValue($field->value, $value, $fieldPath);
106        }
107
108        try {
109            return new $class(...$arguments);
110        } catch (StewartException $e) {
111            throw JsonShapeException::createForReason(JsonShapeError::ObjectRefused, $e, key: $path);
112        }
113    }
114
115    /**
116     * @template T of object
117     * @param class-string<T> $class
118     * @return list<T>
119     * @throws StewartException
120     */
121    public function decodeObjectList(string $class, mixed $data, string $path): array
122    {
123        $items = $this->decodeValue($this->shapes->describeListShape($class, $class), $data, $path);
124        \assert(\is_array($items) && array_is_list($items));
125
126        /** @var list<T> $items */
127        return $items;
128    }
129
130    /**
131     * @return array<string, mixed>|stdClass
132     * @throws StewartException
133     */
134    private function normalizeFields(ClassShape $shape, object $dto): array|stdClass
135    {
136        $normalized = [];
137
138        foreach ($shape->fields as $field) {
139            $value = $dto->{$field->property};
140            $normalized[$field->key] = $value === null || $field->value->passesThrough ? $value : $this->normalizeValue($field->value, $value);
141        }
142
143        return $normalized === [] ? new stdClass() : $normalized;
144    }
145
146    /** @throws StewartException */
147    private function normalizeValue(ValueShape $shape, mixed $value): mixed
148    {
149        if ($value === null) {
150            return null;
151        }
152
153        return match ($shape->kind) {
154            ValueKind::Enum => $this->normalizeEnum($value),
155            ValueKind::Dto => $this->normalizeNestedObject($value),
156            ValueKind::Variant => $this->normalizeVariant($shape, $value),
157            ValueKind::Converted => $this->normalizeConvertedValue($shape, $value),
158            ValueKind::List => $this->normalizeListItems($shape, $value),
159            ValueKind::Map => $this->normalizeMap($value),
160            default => $value,
161        };
162    }
163
164    private function normalizeEnum(mixed $value): int|string
165    {
166        \assert($value instanceof BackedEnum);
167
168        return $value->value;
169    }
170
171    /**
172     * @return array<string, mixed>|stdClass
173     * @throws StewartException
174     */
175    private function normalizeNestedObject(mixed $value): array|stdClass
176    {
177        \assert(\is_object($value));
178
179        return $this->normalizeFields($this->shapes->resolveClassShape($value::class), $value);
180    }
181
182    /**
183     * @return array<string, mixed>
184     * @throws StewartException
185     */
186    private function normalizeVariant(ValueShape $shape, mixed $value): array
187    {
188        \assert(\is_object($value) && $shape->variants !== null);
189        $name = $shape->variants->findVariantName($value) ?? throw new LogicException(\sprintf('%s is not a listed variant of %s.', $value::class, $shape->type));
190
191        $fields = $this->normalizeNestedObject($value);
192
193        return [$shape->variants->key => $name, ...($fields instanceof stdClass ? [] : $fields)];
194    }
195
196    private function normalizeConvertedValue(ValueShape $shape, mixed $value): mixed
197    {
198        \assert(\is_object($value) && $shape->converter !== null);
199
200        return $shape->converter->encodeValue($value);
201    }
202
203    /**
204     * @return array<array-key, mixed>
205     * @throws StewartException
206     */
207    private function normalizeListItems(ValueShape $shape, mixed $value): array
208    {
209        \assert(\is_array($value) && $shape->element !== null);
210        $element = $shape->element;
211
212        return $element->passesThrough ? $value : array_map(fn(mixed $item): mixed => $this->normalizeValue($element, $item), $value);
213    }
214
215    /** @return array<array-key, mixed>|object */
216    private function normalizeMap(mixed $value): array|object
217    {
218        \assert(\is_array($value));
219
220        // Cast so a list-shaped map encodes as a JSON object, not an array.
221        return array_is_list($value) ? (object) $value : $value;
222    }
223
224    /** @throws StewartException */
225    private function decodeValue(ValueShape $shape, mixed $value, string $path): mixed
226    {
227        return match ($shape->kind) {
228            ValueKind::String => \is_string($value) ? $value : throw $this->createWrongTypeException($shape, $path, $value),
229            ValueKind::Int => \is_int($value) ? $value : throw $this->createWrongTypeException($shape, $path, $value),
230            ValueKind::Float => \is_float($value) || \is_int($value) ? (float) $value : throw $this->createWrongTypeException($shape, $path, $value),
231            ValueKind::Number => \is_float($value) || \is_int($value) ? $value : throw $this->createWrongTypeException($shape, $path, $value),
232            ValueKind::Bool => \is_bool($value) ? $value : throw $this->createWrongTypeException($shape, $path, $value),
233            ValueKind::Json => $value,
234            ValueKind::Enum => $this->decodeEnum($shape, $value, $path),
235            ValueKind::Dto => $this->decodeNestedObject($shape, $value, $path),
236            ValueKind::Variant => $this->decodeVariant($shape, $value, $path),
237            ValueKind::Converted => $this->decodeConvertedValue($shape, $value, $path),
238            ValueKind::Map => \is_array($value) ? JsonShape::treatKeysAsStrings($value) : throw $this->createWrongTypeException($shape, $path, $value),
239            ValueKind::Fragment => $this->decodeFragment($shape, $value, $path),
240            ValueKind::List => $this->decodeListItems($shape, $value, $path),
241        };
242    }
243
244    /** @throws StewartException */
245    private function decodeNestedObject(ValueShape $shape, mixed $value, string $path): object
246    {
247        /** @var class-string $class */
248        $class = $shape->type;
249
250        return \is_array($value) ? $this->decodeFields($class, $value, $path) : throw $this->createWrongTypeException($shape, $path, $value);
251    }
252
253    /** @throws StewartException */
254    private function decodeVariant(ValueShape $shape, mixed $value, string $path): object
255    {
256        \assert($shape->variants !== null);
257
258        if (!\is_array($value)) {
259            throw $this->createWrongTypeException($shape, $path, $value);
260        }
261
262        $key = $shape->variants->key;
263        $name = $value[$key] ?? null;
264        $class = \is_string($name) ? $shape->variants->variants[$name] ?? null : null;
265
266        if ($class === null) {
267            throw JsonShapeException::unexpectedValue($path . '.' . $key, 'one of ' . implode(', ', array_keys($shape->variants->variants)), $name);
268        }
269
270        return $this->decodeFields($class, $value, $path);
271    }
272
273    /** @throws StewartException */
274    private function decodeConvertedValue(ValueShape $shape, mixed $value, string $path): mixed
275    {
276        \assert($shape->converter !== null);
277
278        return $shape->converter->decodeValue($value, $path);
279    }
280
281    /** @throws StewartException */
282    private function decodeFragment(ValueShape $shape, mixed $value, string $path): JsonFragment
283    {
284        /** @var class-string<JsonFragment> $fragment */
285        $fragment = $shape->type;
286
287        return $fragment::fromDecodedValue($value, $path, $this);
288    }
289
290    /**
291     * @return list<mixed>
292     * @throws StewartException
293     */
294    private function decodeListItems(ValueShape $shape, mixed $value, string $path): array
295    {
296        if (!\is_array($value) || !array_is_list($value)) {
297            throw $this->createWrongTypeException($shape, $path, $value);
298        }
299
300        \assert($shape->element !== null);
301        $items = [];
302
303        foreach ($value as $index => $item) {
304            $items[] = $this->decodeValue($shape->element, $item, $path . '.' . $index);
305        }
306
307        return $items;
308    }
309
310    /** @throws JsonShapeException */
311    private function decodeEnum(ValueShape $shape, mixed $value, string $path): BackedEnum
312    {
313        $enum = $shape->type;
314        \assert(is_subclass_of($enum, BackedEnum::class));
315
316        if (!(\is_int($value) || \is_string($value)) || get_debug_type($value) !== $shape->enumBackingType) {
317            throw JsonShapeException::wrongType($path, self::describeEnumCases($enum), get_debug_type($value));
318        }
319
320        return $enum::tryFrom($value) ?? throw JsonShapeException::unexpectedValue($path, self::describeEnumCases($enum), $value);
321    }
322
323    /** @param class-string<BackedEnum> $enum */
324    private static function describeEnumCases(string $enum): string
325    {
326        return 'one of ' . implode(', ', array_map(static fn(BackedEnum $case): string => (string) $case->value, $enum::cases()));
327    }
328
329    private function createWrongTypeException(ValueShape $shape, string $path, mixed $value): JsonShapeException
330    {
331        return JsonShapeException::wrongType($path, $shape->describeExpectedValue(), get_debug_type($value));
332    }
333}