Lines 94.02% 63 / 67
Functions and Methods 75.00% 9 / 12
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
ClassShapeReader 94.02% 63 / 67 75.00% 9 / 12 36.28 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 resolveClassShape 100.00% 1 / 1 100.00% 1 / 1 1
 buildClassShape 100.00% 12 / 12 100.00% 1 / 1 4
 buildFieldShape 90.00% 18 / 20 0.00% 0 / 1 9.08
 buildArrayShape 100.00% 4 / 4 100.00% 1 / 1 2
 describeValueShape 100.00% 1 / 1 100.00% 1 / 1 1
 describeListShape 100.00% 1 / 1 100.00% 1 / 1 1
 findConverterForClass 100.00% 1 / 1 100.00% 1 / 1 1
 buildValueShape 100.00% 17 / 17 100.00% 1 / 1 9
 isPublicPromotedProperty 75.00% 3 / 4 0.00% 0 / 1 3.14
 findWireVariants 75.00% 3 / 4 0.00% 0 / 1 3.14
 convertToWireKey 100.00% 1 / 1 100.00% 1 / 1 1
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Json;
6
7use BackedEnum;
8use LogicException;
9use ReflectionClass;
10use ReflectionEnum;
11use ReflectionIntersectionType;
12use ReflectionNamedType;
13use ReflectionParameter;
14use ReflectionProperty;
15use ReflectionUnionType;
16use Stewart\Contracts\Wire\ListOf;
17use Stewart\Contracts\Wire\WireVariants;
18use Stewart\Runtime\Json\Collection\ValueConverterCollection;
19
20final class ClassShapeReader
21{
22    private const array ANY_JSON = ['array', 'bool', 'float', 'int', 'null', 'string'];
23
24    private const array NUMBER = ['float', 'int'];
25
26    private const array SCALARS = [
27        'string' => ValueKind::String,
28        'int' => ValueKind::Int,
29        'float' => ValueKind::Float,
30        'bool' => ValueKind::Bool,
31    ];
32
33    /** @var array<class-string, ClassShape> */
34    private array $classShapes = [];
35
36    /** @var array<class-string, true> */
37    private array $classesBeingDescribed = [];
38
39    /** @var array<string, ValueShape> */
40    private array $valueShapes = [];
41
42    /** @var array<string, ValueShape> */
43    private array $listShapes = [];
44
45    public function __construct(private readonly ValueConverterCollection $converters) {}
46
47    /** @param class-string $class */
48    public function resolveClassShape(string $class): ClassShape
49    {
50        return $this->classShapes[$class] ?? $this->buildClassShape($class);
51    }
52
53    /** @param class-string $class */
54    private function buildClassShape(string $class): ClassShape
55    {
56        if (isset($this->classesBeingDescribed[$class])) {
57            throw new LogicException(\sprintf('%s refers to itself, which the wire cannot carry.', $class));
58        }
59
60        $this->classesBeingDescribed[$class] = true;
61
62        try {
63            $constructor = new ReflectionClass($class)->getConstructor();
64
65            if ($constructor !== null && !$constructor->isPublic()) {
66                throw new LogicException(\sprintf('%s needs a public constructor to be built from the wire.', $class));
67            }
68
69            $fields = array_map(
70                fn(ReflectionParameter $parameter): FieldShape => $this->buildFieldShape($class, $parameter),
71                $constructor?->getParameters() ?? [],
72            );
73
74            return $this->classShapes[$class] = new ClassShape($class, $fields);
75        } finally {
76            unset($this->classesBeingDescribed[$class]);
77        }
78    }
79
80    /** @param class-string $class */
81    private function buildFieldShape(string $class, ReflectionParameter $parameter): FieldShape
82    {
83        $name = $parameter->getName();
84        $where = $class . '::$' . $name;
85
86        if (!self::isPublicPromotedProperty($class, $name)) {
87            throw new LogicException(\sprintf('%s must be a public promoted constructor parameter.', $where));
88        }
89
90        $type = $parameter->getType();
91
92        if ($type instanceof ReflectionUnionType) {
93            $names = array_map(static fn(ReflectionNamedType|ReflectionIntersectionType $part): string => (string) $part, $type->getTypes());
94            sort($names);
95
96            if ($names === self::ANY_JSON) {
97                return new FieldShape($name, $this->convertToWireKey($name), true, new ValueShape(ValueKind::Json));
98            }
99
100            if (array_values(array_diff($names, ['null'])) !== self::NUMBER) {
101                throw new LogicException(\sprintf('%s has a union type the wire cannot carry.', $where));
102            }
103
104            return new FieldShape($name, $this->convertToWireKey($name), $type->allowsNull(), new ValueShape(ValueKind::Number));
105        }
106
107        if (!$type instanceof ReflectionNamedType) {
108            throw new LogicException(\sprintf('%s needs a declared type.', $where));
109        }
110
111        $value = match ($type->getName()) {
112            'mixed' => new ValueShape(ValueKind::Json),
113            'array' => $this->buildArrayShape($parameter, $where),
114            default => $this->describeValueShape($type->getName(), $where),
115        };
116
117        return new FieldShape($name, $this->convertToWireKey($name) . ($value->converter?->keySuffix() ?? ''), $type->allowsNull(), $value);
118    }
119
120    private function buildArrayShape(ReflectionParameter $parameter, string $where): ValueShape
121    {
122        $listOf = $parameter->getAttributes(ListOf::class)[0] ?? null;
123
124        return $listOf === null
125            ? new ValueShape(ValueKind::Map)
126            : $this->describeListShape($listOf->newInstance()->type, $where);
127    }
128
129    public function describeValueShape(string $type, string $where): ValueShape
130    {
131        return $this->valueShapes[$type] ??= $this->buildValueShape($type, $where);
132    }
133
134    public function describeListShape(string $elementType, string $where): ValueShape
135    {
136        return $this->listShapes[$elementType] ??= new ValueShape(ValueKind::List, element: $this->describeValueShape($elementType, $where));
137    }
138
139    public function findConverterForClass(string $class): ?ValueConverter
140    {
141        return $this->converters->findForClass($class);
142    }
143
144    private function buildValueShape(string $type, string $where): ValueShape
145    {
146        if (isset(self::SCALARS[$type])) {
147            return new ValueShape(self::SCALARS[$type], $type);
148        }
149
150        $converter = $this->converters->findForClass($type);
151
152        if ($converter !== null) {
153            return new ValueShape(ValueKind::Converted, $type, converter: $converter);
154        }
155
156        if (is_subclass_of($type, JsonFragment::class)) {
157            return new ValueShape(ValueKind::Fragment, $type);
158        }
159
160        if (is_subclass_of($type, BackedEnum::class)) {
161            return new ValueShape(ValueKind::Enum, $type, enumBackingType: (string) new ReflectionEnum($type)->getBackingType());
162        }
163
164        $variants = self::findWireVariants($type);
165
166        if ($variants !== null) {
167            return new ValueShape(ValueKind::Variant, $type, variants: $variants);
168        }
169
170        if (!class_exists($type) || new ReflectionClass($type)->isAbstract()) {
171            throw new LogicException(\sprintf('%s is a %s, which has no converter.', $where, $type));
172        }
173
174        if ($this->resolveClassShape($type)->holdsFragment) {
175            throw new LogicException(\sprintf('%s nests %s, and only a top-level object may hold a fragment.', $where, $type));
176        }
177
178        return new ValueShape(ValueKind::Dto, $type);
179    }
180
181    // A subclass passes inherited fields through to the parent, which promotes them.
182    /** @param class-string $class */
183    private static function isPublicPromotedProperty(string $class, string $name): bool
184    {
185        if (!property_exists($class, $name)) {
186            return false;
187        }
188
189        $property = new ReflectionProperty($class, $name);
190
191        return $property->isPromoted() && $property->isPublic();
192    }
193
194    private static function findWireVariants(string $type): ?WireVariants
195    {
196        if (!class_exists($type) && !interface_exists($type)) {
197            return null;
198        }
199
200        $attribute = new ReflectionClass($type)->getAttributes(WireVariants::class)[0] ?? null;
201
202        return $attribute?->newInstance();
203    }
204
205    private function convertToWireKey(string $propertyName): string
206    {
207        return strtolower((string) preg_replace('/(?<!^)[A-Z]/', '_$0', $propertyName));
208    }
209}