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

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

23 Mar 2026 08:31PM UTC coverage: 98.58% (-0.1%) from 98.693%
23458676927

Pull #120

github

web-flow
Merge abb6f5013 into d14ae3d85
Pull Request #120: Fix/issue 98

568 of 579 new or added lines in 54 files covered. (98.1%)

3889 of 3945 relevant lines covered (98.58%)

553.63 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(
636✔
38
        PropertyMetaDataCollection $propertyMetaDataCollection,
39
        SchemaProcessor $schemaProcessor,
40
        Schema $schema,
41
        private readonly bool $rootLevelComposition,
42
    ) {
43
        parent::__construct($propertyMetaDataCollection, $schemaProcessor, $schema);
636✔
44
    }
45

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

53
        if (
54
            empty($json[$propertySchema->getJson()['type']]) &&
636✔
55
            $this->schemaProcessor->getGeneratorConfiguration()->isOutputEnabled()
636✔
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);
636✔
63

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

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

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

87
        $property->addValidator(
636✔
88
            new ComposedPropertyValidator(
636✔
89
                $this->schemaProcessor->getGeneratorConfiguration(),
636✔
90
                $property,
636✔
91
                $compositionProperties,
636✔
92
                static::class,
636✔
93
                [
636✔
94
                    'compositionProperties' => $compositionProperties,
636✔
95
                    'schema' => $this->schema,
636✔
96
                    'generatorConfiguration' => $this->schemaProcessor->getGeneratorConfiguration(),
636✔
97
                    'viewHelper' => new RenderHelper($this->schemaProcessor->getGeneratorConfiguration()),
636✔
98
                    'availableAmount' => $availableAmount,
636✔
99
                    'composedValueValidation' => $this->getComposedValueValidation($availableAmount),
636✔
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,
636✔
104
                    'mergedProperty' => &$this->mergedProperty,
636✔
105
                    'onlyForDefinedValues' =>
636✔
106
                        $propertySchema->getJson()['onlyForDefinedValues']
636✔
107
                        && $this instanceof ComposedPropertiesInterface,
636✔
108
                ],
636✔
109
            ),
636✔
110
            100,
636✔
111
        );
636✔
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
636✔
122
    {
123
        $propertyFactory = new PropertyFactory(new PropertyProcessorFactory());
636✔
124
        $compositionProperties = [];
636✔
125
        $json = $propertySchema->getJson()['propertySchema']->getJson();
636✔
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());
636✔
130

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

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

147
            $compositionProperty->onResolve(function () use ($compositionProperty, $property): void {
618✔
148
                $compositionProperty->filterValidators(
618✔
149
                    static fn(Validator $validator): bool =>
618✔
150
                        !is_a($validator->getValidator(), RequiredPropertyValidator::class) &&
618✔
151
                        !is_a($validator->getValidator(), ComposedPropertyValidator::class)
618✔
152
                );
618✔
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())) {
618✔
159
                    $property->addTypeHintDecorator(new CompositionTypeHintDecorator($compositionProperty));
368✔
160
                }
161
            });
618✔
162

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

166
        return $compositionProperties;
636✔
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
618✔
175
    {
176
        if ($this instanceof NotProcessor) {
618✔
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) {
526✔
183
            if ($compositionProperty->getNestedSchema() !== null) {
526✔
184
                return;
398✔
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