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

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

23 Mar 2026 01:55PM UTC coverage: 98.584% (-0.001%) from 98.585%
23440965067

Pull #118

github

Enno Woortmann
Merge fix/issue-110 into chore/phpunit-13-upgrade

Brings in patternProperties type intersection, PSR-12 code style
enforcement, PropertyMerger API refactor, and all related tests and
documentation. Resolved conflicts by keeping readonly constructors and
PHP 8.4+ style from this branch, applying phpcbf to align opening
braces with the PSR-12 rule. Added squizlabs/php_codesniffer to
require-dev alongside phpunit ^13.0.
Pull Request #118: Upgrade to PHP 8.4 minimum and PHPUnit 13

508 of 517 new or added lines in 54 files covered. (98.26%)

23 existing lines in 9 files now uncovered.

3828 of 3883 relevant lines covered (98.58%)

548.12 hits per line

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

99.03
/src/PropertyProcessor/Property/BaseProcessor.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace PHPModelGenerator\PropertyProcessor\Property;
6

7
use PHPMicroTemplate\Exception\FileSystemException;
8
use PHPMicroTemplate\Exception\SyntaxErrorException;
9
use PHPMicroTemplate\Exception\UndefinedSymbolException;
10
use PHPModelGenerator\Exception\Object\MaxPropertiesException;
11
use PHPModelGenerator\Exception\Object\MinPropertiesException;
12
use PHPModelGenerator\Exception\SchemaException;
13
use PHPModelGenerator\Model\Property\BaseProperty;
14
use PHPModelGenerator\Model\Property\CompositionPropertyDecorator;
15
use PHPModelGenerator\Model\Property\Property;
16
use PHPModelGenerator\Model\Property\PropertyInterface;
17
use PHPModelGenerator\Model\Property\PropertyType;
18
use PHPModelGenerator\Model\SchemaDefinition\JsonSchema;
19
use PHPModelGenerator\Model\Validator;
20
use PHPModelGenerator\Model\Validator\AbstractComposedPropertyValidator;
21
use PHPModelGenerator\Exception\Generic\DeniedPropertyException;
22
use PHPModelGenerator\Model\Validator\AdditionalPropertiesValidator;
23
use PHPModelGenerator\Model\Validator\ComposedPropertyValidator;
24
use PHPModelGenerator\Model\Validator\ConditionalPropertyValidator;
25
use PHPModelGenerator\Model\Validator\NoAdditionalPropertiesValidator;
26
use PHPModelGenerator\Model\Validator\PatternPropertiesValidator;
27
use PHPModelGenerator\Model\Validator\PropertyNamesValidator;
28
use PHPModelGenerator\Model\Validator\PropertyTemplateValidator;
29
use PHPModelGenerator\Model\Validator\PropertyValidator;
30
use PHPModelGenerator\PropertyProcessor\ComposedValue\AllOfProcessor;
31
use PHPModelGenerator\PropertyProcessor\ComposedValue\ComposedPropertiesInterface;
32
use PHPModelGenerator\PropertyProcessor\PropertyMetaDataCollection;
33
use PHPModelGenerator\PropertyProcessor\PropertyFactory;
34
use PHPModelGenerator\PropertyProcessor\PropertyProcessorFactory;
35

36
/**
37
 * Class BaseObjectProcessor
38
 *
39
 * @package PHPModelGenerator\PropertyProcessor\Property
40
 */
41
class BaseProcessor extends AbstractPropertyProcessor
42
{
43
    protected const TYPE = 'object';
44

45
    private const string COUNT_PROPERTIES =
46
        'count(
47
            array_unique(
48
                array_merge(
49
                    array_keys($this->_rawModelDataInput),
50
                    array_keys($modelData),
51
                )
52
            ),
53
        )';
54

55
    /**
56
     * @inheritdoc
57
     *
58
     * @throws FileSystemException
59
     * @throws SchemaException
60
     * @throws SyntaxErrorException
61
     * @throws UndefinedSymbolException
62
     */
63
    public function process(string $propertyName, JsonSchema $propertySchema): PropertyInterface
2,060✔
64
    {
65
        $this->schema
2,060✔
66
            ->getSchemaDictionary()
2,060✔
67
            ->setUpDefinitionDictionary($this->schemaProcessor, $this->schema);
2,060✔
68

69
        // create a property which is used to gather composed properties validators.
70
        $property = new BaseProperty($propertyName, new PropertyType(static::TYPE), $propertySchema);
2,060✔
71
        $this->generateValidators($property, $propertySchema);
2,060✔
72

73
        $this->addPropertiesToSchema($propertySchema);
2,059✔
74
        $this->transferComposedPropertiesToSchema($property);
2,001✔
75

76
        $this->addPropertyNamesValidator($propertySchema);
2,000✔
77
        $this->addPatternPropertiesValidator($propertySchema);
1,999✔
78
        $this->addAdditionalPropertiesValidator($propertySchema);
1,998✔
79

80
        $this->addMinPropertiesValidator($propertyName, $propertySchema);
1,998✔
81
        $this->addMaxPropertiesValidator($propertyName, $propertySchema);
1,998✔
82

83
        return $property;
1,998✔
84
    }
85

86
    /**
87
     * Add a validator to check all provided property names
88
     *
89
     * @throws SchemaException
90
     * @throws FileSystemException
91
     * @throws SyntaxErrorException
92
     * @throws UndefinedSymbolException
93
     */
94
    protected function addPropertyNamesValidator(JsonSchema $propertySchema): void
2,000✔
95
    {
96
        if (!isset($propertySchema->getJson()['propertyNames'])) {
2,000✔
97
            return;
1,956✔
98
        }
99

100
        $this->schema->addBaseValidator(
44✔
101
            new PropertyNamesValidator(
44✔
102
                $this->schemaProcessor,
44✔
103
                $this->schema,
44✔
104
                $propertySchema->withJson($propertySchema->getJson()['propertyNames']),
44✔
105
            )
44✔
106
        );
44✔
107
    }
108

109
    /**
110
     * Add an object validator to specify constraints for properties which are not defined in the schema
111
     *
112
     * @throws FileSystemException
113
     * @throws SchemaException
114
     * @throws SyntaxErrorException
115
     * @throws UndefinedSymbolException
116
     */
117
    protected function addAdditionalPropertiesValidator(JsonSchema $propertySchema): void
1,998✔
118
    {
119
        $json = $propertySchema->getJson();
1,998✔
120

121
        if (
122
            !isset($json['additionalProperties']) &&
1,998✔
123
            $this->schemaProcessor->getGeneratorConfiguration()->denyAdditionalProperties()
1,998✔
124
        ) {
125
            $json['additionalProperties'] = false;
5✔
126
        }
127

128
        if (!isset($json['additionalProperties']) || $json['additionalProperties'] === true) {
1,998✔
129
            return;
1,920✔
130
        }
131

132
        if (!is_bool($json['additionalProperties'])) {
230✔
133
            $this->schema->addBaseValidator(
88✔
134
                new AdditionalPropertiesValidator(
88✔
135
                    $this->schemaProcessor,
88✔
136
                    $this->schema,
88✔
137
                    $propertySchema,
88✔
138
                )
88✔
139
            );
88✔
140

141
            return;
88✔
142
        }
143

144
        $this->schema->addBaseValidator(
142✔
145
            new NoAdditionalPropertiesValidator(
142✔
146
                new Property($this->schema->getClassName(), null, $propertySchema),
142✔
147
                $json,
142✔
148
            )
142✔
149
        );
142✔
150
    }
151

152
    /**
153
     * @throws SchemaException
154
     */
155
    protected function addPatternPropertiesValidator(JsonSchema $propertySchema): void
1,999✔
156
    {
157
        $json = $propertySchema->getJson();
1,999✔
158

159
        if (!isset($json['patternProperties'])) {
1,999✔
160
            return;
1,942✔
161
        }
162

163
        foreach ($json['patternProperties'] as $pattern => $schema) {
59✔
164
            $escapedPattern = addcslashes((string) $pattern, '/');
59✔
165

166
            if (@preg_match("/$escapedPattern/", '') === false) {
59✔
167
                throw new SchemaException(
1✔
168
                    "Invalid pattern '$pattern' for pattern property in file {$propertySchema->getFile()}",
1✔
169
                );
1✔
170
            }
171

172
            $validator = new PatternPropertiesValidator(
58✔
173
                $this->schemaProcessor,
58✔
174
                $this->schema,
58✔
175
                $pattern,
58✔
176
                $propertySchema->withJson($schema),
58✔
177
            );
58✔
178

179
            $this->schema->addBaseValidator($validator);
58✔
180
        }
181
    }
182

183
    /**
184
     * Add an object validator to limit the amount of provided properties
185
     *
186
     * @throws SchemaException
187
     */
188
    protected function addMaxPropertiesValidator(string $propertyName, JsonSchema $propertySchema): void
1,998✔
189
    {
190
        $json = $propertySchema->getJson();
1,998✔
191

192
        if (!isset($json['maxProperties'])) {
1,998✔
193
            return;
1,965✔
194
        }
195

196
        $this->schema->addBaseValidator(
41✔
197
            new PropertyValidator(
41✔
198
                new Property($propertyName, null, $propertySchema),
41✔
199
                sprintf(
41✔
200
                    '%s > %d',
41✔
201
                    self::COUNT_PROPERTIES,
41✔
202
                    $json['maxProperties'],
41✔
203
                ),
41✔
204
                MaxPropertiesException::class,
41✔
205
                [$json['maxProperties']],
41✔
206
            )
41✔
207
        );
41✔
208
    }
209

210
    /**
211
     * Add an object validator to force at least the defined amount of properties to be provided
212
     *
213
     * @throws SchemaException
214
     */
215
    protected function addMinPropertiesValidator(string $propertyName, JsonSchema $propertySchema): void
1,998✔
216
    {
217
        $json = $propertySchema->getJson();
1,998✔
218

219
        if (!isset($json['minProperties'])) {
1,998✔
220
            return;
1,983✔
221
        }
222

223
        $this->schema->addBaseValidator(
23✔
224
            new PropertyValidator(
23✔
225
                new Property($propertyName, null, $propertySchema),
23✔
226
                sprintf(
23✔
227
                    '%s < %d',
23✔
228
                    self::COUNT_PROPERTIES,
23✔
229
                    $json['minProperties'],
23✔
230
                ),
23✔
231
                MinPropertiesException::class,
23✔
232
                [$json['minProperties']],
23✔
233
            )
23✔
234
        );
23✔
235
    }
236

237
    /**
238
     * Add the properties defined in the JSON schema to the current schema model
239
     *
240
     * @throws SchemaException
241
     */
242
    protected function addPropertiesToSchema(JsonSchema $propertySchema): void
2,059✔
243
    {
244
        $json = $propertySchema->getJson();
2,059✔
245

246
        $propertyFactory = new PropertyFactory(new PropertyProcessorFactory());
2,059✔
247
        $propertyMetaDataCollection = new PropertyMetaDataCollection(
2,059✔
248
            $json['required'] ?? [],
2,059✔
249
            $json['dependencies'] ?? [],
2,059✔
250
        );
2,059✔
251

252
        $json['properties'] ??= [];
2,059✔
253
        // setup empty properties for required properties which aren't defined in the properties section of the schema
254
        $json['properties'] += array_fill_keys(
2,059✔
255
            array_diff($json['required'] ?? [], array_keys($json['properties'])),
2,059✔
256
            [],
2,059✔
257
        );
2,059✔
258

259
        foreach ($json['properties'] as $propertyName => $propertyStructure) {
2,059✔
260
            if ($propertyStructure === false) {
1,992✔
261
                if (in_array($propertyName, $json['required'] ?? [], true)) {
13✔
262
                    throw new SchemaException(
1✔
263
                        sprintf(
1✔
264
                            "Property '%s' is denied (schema false) but also listed as required in file %s",
1✔
265
                            $propertyName,
1✔
266
                            $propertySchema->getFile(),
1✔
267
                        ),
1✔
268
                    );
1✔
269
                }
270

271
                $this->schema->addBaseValidator(
12✔
272
                    new PropertyValidator(
12✔
273
                        new Property($propertyName, null, $propertySchema->withJson([])),
12✔
274
                        "array_key_exists('" . addslashes($propertyName) . "', \$modelData)",
12✔
275
                        DeniedPropertyException::class,
12✔
276
                    )
12✔
277
                );
12✔
278
                continue;
12✔
279
            }
280

281
            $this->schema->addProperty(
1,991✔
282
                $propertyFactory->create(
1,991✔
283
                    $propertyMetaDataCollection,
1,991✔
284
                    $this->schemaProcessor,
1,991✔
285
                    $this->schema,
1,991✔
286
                    (string) $propertyName,
1,991✔
287
                    $propertySchema->withJson($propertyStructure),
1,991✔
288
                )
1,991✔
289
            );
1,991✔
290
        }
291
    }
292

293
    /**
294
     * Transfer properties of composed properties to the current schema to offer a complete model including all
295
     * composed properties.
296
     *
297
     * @throws SchemaException
298
     */
299
    protected function transferComposedPropertiesToSchema(PropertyInterface $property): void
2,001✔
300
    {
301
        foreach ($property->getValidators() as $validator) {
2,001✔
302
            $validator = $validator->getValidator();
2,001✔
303

304
            if (!is_a($validator, AbstractComposedPropertyValidator::class)) {
2,001✔
305
                continue;
2,001✔
306
            }
307

308
            // If the transferred validator of the composed property is also a composed property strip the nested
309
            // composition validations from the added validator. The nested composition will be validated in the object
310
            // generated for the nested composition which will be executed via an instantiation. Consequently, the
311
            // validation must not be executed in the outer composition.
312
            $this->schema->addBaseValidator(
263✔
313
                ($validator instanceof ComposedPropertyValidator)
263✔
314
                    ? $validator->withoutNestedCompositionValidation()
240✔
315
                    : $validator,
263✔
316
            );
263✔
317

318
            if (!is_a($validator->getCompositionProcessor(), ComposedPropertiesInterface::class, true)) {
263✔
UNCOV
319
                continue;
×
320
            }
321

322
            foreach ($validator->getComposedProperties() as $composedProperty) {
263✔
323
                $composedProperty->onResolve(function () use ($composedProperty, $property, $validator): void {
263✔
324
                    if (!$composedProperty->getNestedSchema()) {
263✔
325
                        throw new SchemaException(
1✔
326
                            sprintf(
1✔
327
                                "No nested schema for composed property %s in file %s found",
1✔
328
                                $property->getName(),
1✔
329
                                $property->getJsonSchema()->getFile(),
1✔
330
                            )
1✔
331
                        );
1✔
332
                    }
333

334
                    $composedProperty->getNestedSchema()->onAllPropertiesResolved(
262✔
335
                        function () use ($composedProperty, $validator): void {
262✔
336
                            foreach ($composedProperty->getNestedSchema()->getProperties() as $property) {
262✔
337
                                $this->schema->addProperty(
262✔
338
                                    $this->cloneTransferredProperty(
262✔
339
                                        $property,
262✔
340
                                        $validator->getCompositionProcessor(),
262✔
341
                                        $composedProperty,
262✔
342
                                        $validator,
262✔
343
                                    ),
262✔
344
                                    $validator->getCompositionProcessor(),
262✔
345
                                );
262✔
346

347
                                $composedProperty->appendAffectedObjectProperty($property);
260✔
348
                            }
349
                        },
262✔
350
                    );
262✔
351
                });
263✔
352
            }
353
        }
354
    }
355

356
    /**
357
     * Clone the provided property to transfer it to a schema. Sets the nullability and required flag based on the
358
     * composition processor used to set up the composition. Widens the type to mixed when the property is exclusive
359
     * to one anyOf/oneOf branch and at least one other branch allows additional properties, preventing TypeError when
360
     * raw input values of an arbitrary type are stored in the property slot.
361
     *
362
     * For ConditionalPropertyValidator (if/then/else), the widening check uses only the data branches
363
     * (then/else), not the if condition branch, since the if block is a filter and not a competing
364
     * data branch for type-widening purposes.
365
     */
366
    private function cloneTransferredProperty(
262✔
367
        PropertyInterface $property,
368
        string $compositionProcessor,
369
        CompositionPropertyDecorator $sourceBranch,
370
        AbstractComposedPropertyValidator $validator,
371
    ): PropertyInterface {
372
        $transferredProperty = (clone $property)
262✔
373
            ->filterValidators(static fn(Validator $validator): bool =>
262✔
374
                is_a($validator->getValidator(), PropertyTemplateValidator::class));
262✔
375

376
        if (!is_a($compositionProcessor, AllOfProcessor::class, true)) {
262✔
377
            $transferredProperty->setRequired(false);
164✔
378

379
            if ($transferredProperty->getType()) {
164✔
380
                $transferredProperty->setType(
164✔
381
                    new PropertyType($transferredProperty->getType()->getNames(), true),
164✔
382
                    new PropertyType($transferredProperty->getType(true)->getNames(), true),
164✔
383
                );
164✔
384
            }
385

386
            $wideningBranches = $validator instanceof ConditionalPropertyValidator
164✔
387
                ? $validator->getDataBranches()
37✔
388
                : $validator->getComposedProperties();
127✔
389

390
            if ($this->exclusiveBranchPropertyNeedsWidening($property->getName(), $sourceBranch, $wideningBranches)) {
164✔
391
                $transferredProperty->setType(null, null, reset: true);
129✔
392
            }
393
        }
394

395
        return $transferredProperty;
262✔
396
    }
397

398
    /**
399
     * Returns true when the property named $propertyName is exclusive to $sourceBranch and at least
400
     * one other anyOf/oneOf branch allows additional properties (i.e. does NOT declare
401
     * additionalProperties: false). In that case the property slot can receive an arbitrarily-typed
402
     * raw input value from a non-matching branch, so the native type hint must be removed.
403
     *
404
     * Returns false when the property appears in another branch too (Phase 6 handles that via
405
     * Schema::addProperty merging) or when all other branches have additionalProperties: false
406
     * (making the property mutually exclusive with the other branches' properties).
407
     *
408
     * @param CompositionPropertyDecorator[] $allBranches
409
     */
410
    private function exclusiveBranchPropertyNeedsWidening(
164✔
411
        string $propertyName,
412
        CompositionPropertyDecorator $sourceBranch,
413
        array $allBranches,
414
    ): bool {
415
        // Pass 1: if any other branch defines the same property, Phase 6 handles the type
416
        // merging via Schema::addProperty — widening to mixed is not needed here.
417
        foreach ($allBranches as $branch) {
164✔
418
            if ($branch === $sourceBranch) {
164✔
419
                continue;
164✔
420
            }
421

422
            $branchPropertyNames = $branch->getNestedSchema()
163✔
423
                ? array_map(
163✔
424
                    static fn(PropertyInterface $p): string => $p->getName(),
163✔
425
                    $branch->getNestedSchema()->getProperties(),
163✔
426
                )
163✔
UNCOV
427
                : [];
×
428

429
            if (in_array($propertyName, $branchPropertyNames, true)) {
163✔
430
                return false;
66✔
431
            }
432
        }
433

434
        // Pass 2: the property is exclusive to $sourceBranch. Widening is needed when at
435
        // least one other branch allows additional properties — an arbitrary input value can
436
        // then land in this slot when that branch is the one that matched.
437
        foreach ($allBranches as $branch) {
131✔
438
            if ($branch === $sourceBranch) {
131✔
439
                continue;
101✔
440
            }
441

442
            if (($branch->getBranchSchema()->getJson()['additionalProperties'] ?? true) !== false) {
130✔
443
                return true;
129✔
444
            }
445
        }
446

447
        // All other branches have additionalProperties:false — no arbitrary value can arrive.
448
        return false;
8✔
449
    }
450
}
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