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

wol-soft / php-json-schema-model-generator / 23458742876

23 Mar 2026 08:33PM UTC coverage: 98.605% (-0.09%) from 98.693%
23458742876

push

github

web-flow
Merge pull request #115 from wol-soft/fix/issue-110

Type system (Type widening for compositions, union types). Fixes #110 and #114.

544 of 554 new or added lines in 51 files covered. (98.19%)

3887 of 3942 relevant lines covered (98.6%)

547.23 hits per line

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

99.12
/src/PropertyProcessor/ComposedValue/AbstractComposedValueProcessor.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace PHPModelGenerator\PropertyProcessor\ComposedValue;
6

7
use PHPModelGenerator\Exception\SchemaException;
8
use PHPModelGenerator\Model\Property\CompositionPropertyDecorator;
9
use PHPModelGenerator\Model\Property\PropertyInterface;
10
use PHPModelGenerator\Model\Property\PropertyType;
11
use PHPModelGenerator\Model\Schema;
12
use PHPModelGenerator\Model\SchemaDefinition\JsonSchema;
13
use PHPModelGenerator\Model\Validator;
14
use PHPModelGenerator\Model\Validator\ComposedPropertyValidator;
15
use PHPModelGenerator\Model\Validator\RequiredPropertyValidator;
16
use PHPModelGenerator\PropertyProcessor\Decorator\TypeHint\ClearTypeHintDecorator;
17
use PHPModelGenerator\PropertyProcessor\Decorator\TypeHint\CompositionTypeHintDecorator;
18
use PHPModelGenerator\PropertyProcessor\Property\AbstractValueProcessor;
19
use PHPModelGenerator\PropertyProcessor\PropertyMetaDataCollection;
20
use PHPModelGenerator\PropertyProcessor\PropertyFactory;
21
use PHPModelGenerator\PropertyProcessor\PropertyProcessorFactory;
22
use PHPModelGenerator\SchemaProcessor\SchemaProcessor;
23
use PHPModelGenerator\Utils\RenderHelper;
24

25
/**
26
 * Class AbstractComposedValueProcessor
27
 *
28
 * @package PHPModelGenerator\PropertyProcessor\ComposedValue
29
 */
30
abstract class AbstractComposedValueProcessor extends AbstractValueProcessor
31
{
32
    private ?PropertyInterface $mergedProperty = null;
33

34
    /**
35
     * AbstractComposedValueProcessor constructor.
36
     */
37
    public function __construct(
613✔
38
        PropertyMetaDataCollection $propertyMetaDataCollection,
39
        SchemaProcessor $schemaProcessor,
40
        Schema $schema,
41
        private bool $rootLevelComposition,
42
    ) {
43
        parent::__construct($propertyMetaDataCollection, $schemaProcessor, $schema);
613✔
44
    }
45

46
    /**
47
     * @inheritdoc
48
     */
49
    protected function generateValidators(PropertyInterface $property, JsonSchema $propertySchema): void
613✔
50
    {
51
        $json = $propertySchema->getJson()['propertySchema']->getJson();
613✔
52

53
        if (
54
            empty($json[$propertySchema->getJson()['type']]) &&
613✔
55
            $this->schemaProcessor->getGeneratorConfiguration()->isOutputEnabled()
613✔
56
        ) {
57
            // @codeCoverageIgnoreStart
58
            echo "Warning: empty composition for {$property->getName()} may lead to unexpected results\n";
59
            // @codeCoverageIgnoreEnd
60
        }
61

62
        $compositionProperties = $this->getCompositionProperties($property, $propertySchema);
613✔
63

64
        $resolvedCompositions = 0;
613✔
65
        foreach ($compositionProperties as $compositionProperty) {
613✔
66
            $compositionProperty->onResolve(
595✔
67
                function () use (&$resolvedCompositions, $property, $compositionProperties, $propertySchema): void {
595✔
68
                    if (++$resolvedCompositions === count($compositionProperties)) {
595✔
69
                        $this->transferPropertyType($property, $compositionProperties);
595✔
70

71
                        $this->mergedProperty = !$this->rootLevelComposition
595✔
72
                            && $this instanceof MergedComposedPropertiesInterface
595✔
73
                                ? $this->schemaProcessor->createMergedProperty(
184✔
74
                                    $this->schema,
184✔
75
                                    $property,
184✔
76
                                    $compositionProperties,
184✔
77
                                    $propertySchema,
184✔
78
                                )
184✔
79
                                : null;
427✔
80
                    }
81
                },
595✔
82
            );
595✔
83
        }
84

85
        $availableAmount = count($compositionProperties);
613✔
86

87
        $property->addValidator(
613✔
88
            new ComposedPropertyValidator(
613✔
89
                $this->schemaProcessor->getGeneratorConfiguration(),
613✔
90
                $property,
613✔
91
                $compositionProperties,
613✔
92
                static::class,
613✔
93
                [
613✔
94
                    'compositionProperties' => $compositionProperties,
613✔
95
                    'schema' => $this->schema,
613✔
96
                    'generatorConfiguration' => $this->schemaProcessor->getGeneratorConfiguration(),
613✔
97
                    'viewHelper' => new RenderHelper($this->schemaProcessor->getGeneratorConfiguration()),
613✔
98
                    'availableAmount' => $availableAmount,
613✔
99
                    'composedValueValidation' => $this->getComposedValueValidation($availableAmount),
613✔
100
                    // if the property is a composed property the resulting value of a validation must be proposed
101
                    // to be the final value after the validations (e.g. object instantiations may be performed).
102
                    // Otherwise (eg. a NotProcessor) the value must be proposed before the validation
103
                    'postPropose' => $this instanceof ComposedPropertiesInterface,
613✔
104
                    'mergedProperty' => &$this->mergedProperty,
613✔
105
                    'onlyForDefinedValues' =>
613✔
106
                        $propertySchema->getJson()['onlyForDefinedValues']
613✔
107
                        && $this instanceof ComposedPropertiesInterface,
613✔
108
                ],
613✔
109
            ),
613✔
110
            100,
613✔
111
        );
613✔
112
    }
113

114
    /**
115
     * Set up composition properties for the given property schema
116
     *
117
     * @return CompositionPropertyDecorator[]
118
     *
119
     * @throws SchemaException
120
     */
121
    protected function getCompositionProperties(PropertyInterface $property, JsonSchema $propertySchema): array
613✔
122
    {
123
        $propertyFactory = new PropertyFactory(new PropertyProcessorFactory());
613✔
124
        $compositionProperties = [];
613✔
125
        $json = $propertySchema->getJson()['propertySchema']->getJson();
613✔
126

127
        // clear the base type of the property to keep only the types of the composition.
128
        // This avoids e.g. "array|int[]" for a property which is known to contain always an integer array
129
        $property->addTypeHintDecorator(new ClearTypeHintDecorator());
613✔
130

131
        foreach ($json[$propertySchema->getJson()['type']] as $compositionElement) {
613✔
132
            $compositionSchema = $propertySchema->getJson()['propertySchema']->withJson($compositionElement);
595✔
133

134
            $compositionProperty = new CompositionPropertyDecorator(
595✔
135
                $property->getName(),
595✔
136
                $compositionSchema,
595✔
137
                $propertyFactory
595✔
138
                    ->create(
595✔
139
                        new PropertyMetaDataCollection([$property->getName() => $property->isRequired()]),
595✔
140
                        $this->schemaProcessor,
595✔
141
                        $this->schema,
595✔
142
                        $property->getName(),
595✔
143
                        $compositionSchema,
595✔
144
                    )
595✔
145
            );
595✔
146

147
            $compositionProperty->onResolve(function () use ($compositionProperty, $property): void {
595✔
148
                $compositionProperty->filterValidators(
595✔
149
                    static fn(Validator $validator): bool =>
595✔
150
                        !is_a($validator->getValidator(), RequiredPropertyValidator::class) &&
595✔
151
                        !is_a($validator->getValidator(), ComposedPropertyValidator::class)
595✔
152
                );
595✔
153

154
                // only create a composed type hint if we aren't a AnyOf or an AllOf processor and the
155
                // compositionProperty contains no object. This results in objects being composed each separately for a
156
                // OneOf processor (e.g. string|ObjectA|ObjectB). For a merged composed property the objects are merged
157
                // together, so it results in string|MergedObject
158
                if (!($this instanceof MergedComposedPropertiesInterface && $compositionProperty->getNestedSchema())) {
595✔
159
                    $property->addTypeHintDecorator(new CompositionTypeHintDecorator($compositionProperty));
361✔
160
                }
161
            });
595✔
162

163
            $compositionProperties[] = $compositionProperty;
595✔
164
        }
165

166
        return $compositionProperties;
613✔
167
    }
168

169
    /**
170
     * Check if the provided property can inherit a single type from the composition properties.
171
     *
172
     * @param CompositionPropertyDecorator[] $compositionProperties
173
     */
174
    private function transferPropertyType(PropertyInterface $property, array $compositionProperties): void
595✔
175
    {
176
        if ($this instanceof NotProcessor) {
595✔
177
            return;
92✔
178
        }
179

180
        // Skip widening when any branch has a nested schema (object): the merged-property
181
        // mechanism creates a combined class whose name is not among the per-branch type names.
182
        foreach ($compositionProperties as $compositionProperty) {
503✔
183
            if ($compositionProperty->getNestedSchema() !== null) {
503✔
184
                return;
375✔
185
            }
186
        }
187

188
        // Flatten all type names from all branches. Use getNames() to handle branches that
189
        // already carry a union PropertyType.
190
        $allNames = array_merge(...array_map(
129✔
191
            static fn(CompositionPropertyDecorator $compositionProperty): array =>
129✔
192
                $compositionProperty->getType() ? $compositionProperty->getType()->getNames() : [],
129✔
193
            $compositionProperties,
129✔
194
        ));
129✔
195

196
        // A branch with no type contributes nothing but signals that nullable=true is required.
197
        $hasBranchWithNoType = array_filter(
129✔
198
            $compositionProperties,
129✔
199
            static fn(CompositionPropertyDecorator $compositionProperty): bool =>
129✔
200
                $compositionProperty->getType() === null,
129✔
201
        ) !== [];
129✔
202

203
        // An optional branch (property not required in that branch) means the property can be
204
        // absent at runtime, causing the root getter to return null. This is a structural
205
        // nullable — independent of the implicit-null configuration setting.
206
        //
207
        // For oneOf/anyOf: any optional branch makes the property nullable (the branch that
208
        // omits the property can match, leaving the value as null).
209
        //
210
        // For allOf: all branches must hold simultaneously. If at least one branch marks the
211
        // property as required, the property is required overall — an optional branch in allOf
212
        // does not by itself make the property nullable. Only if NO branch requires the property
213
        // (i.e. the property is optional across all allOf branches) is it structurally nullable.
214
        $hasBranchWithRequiredProperty = array_filter(
129✔
215
            $compositionProperties,
129✔
216
            static fn(CompositionPropertyDecorator $compositionProperty): bool =>
129✔
217
                $compositionProperty->isRequired(),
129✔
218
        ) !== [];
129✔
219
        $hasBranchWithOptionalProperty = $this instanceof AllOfProcessor
129✔
220
            ? !$hasBranchWithRequiredProperty
25✔
221
            : array_filter(
104✔
222
                $compositionProperties,
104✔
223
                static fn(CompositionPropertyDecorator $compositionProperty): bool =>
104✔
224
                    !$compositionProperty->isRequired(),
104✔
225
            ) !== [];
104✔
226

227
        // Strip 'null' → nullable flag; PropertyType constructor deduplicates the rest.
228
        $hasNull = in_array('null', $allNames, true);
129✔
229
        $nonNullNames = array_values(array_filter(
129✔
230
            array_unique($allNames),
129✔
231
            fn(string $t): bool => $t !== 'null',
129✔
232
        ));
129✔
233

234
        if (!$nonNullNames) {
129✔
NEW
235
            return;
×
236
        }
237

238
        $nullable = ($hasNull || $hasBranchWithNoType || $hasBranchWithOptionalProperty) ? true : null;
129✔
239

240
        $property->setType(new PropertyType($nonNullNames, $nullable));
129✔
241
    }
242

243
    /**
244
     * @param int $composedElements The amount of elements which are composed together
245
     */
246
    abstract protected function getComposedValueValidation(int $composedElements): string;
247
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc