Skip to content

Commit 3886d6b

Browse files
committed
feat: Add support for dependentRequired
1 parent f179f10 commit 3886d6b

3 files changed

Lines changed: 52 additions & 0 deletions

File tree

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace JsonSchema\Constraints\Drafts\Draft2019;
6+
7+
use JsonSchema\ConstraintError;
8+
use JsonSchema\Constraints\ConstraintInterface;
9+
use JsonSchema\Entity\ErrorBagProxy;
10+
use JsonSchema\Entity\JsonPointer;
11+
12+
class DependentRequiredConstraint implements ConstraintInterface
13+
{
14+
use ErrorBagProxy;
15+
16+
/** @var Factory */
17+
private $factory;
18+
19+
public function __construct(?Factory $factory = null)
20+
{
21+
$this->factory = $factory ?: new Factory();
22+
$this->initialiseErrorBag($this->factory);
23+
}
24+
25+
public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void
26+
{
27+
if (!property_exists($schema, 'dependentRequired')) {
28+
return;
29+
}
30+
31+
if (!is_object($value)) {
32+
return;
33+
}
34+
35+
foreach ($schema->dependentRequired as $dependant => $dependencies) {
36+
if (!property_exists($value, $dependant)) {
37+
continue;
38+
}
39+
40+
foreach ($dependencies as $dependency) {
41+
if (!property_exists($value, $dependency)) {
42+
$this->addError(ConstraintError::DEPENDENCIES(), $path, [
43+
'dependant' => $dependant,
44+
'dependency' => $dependency,
45+
]);
46+
}
47+
}
48+
}
49+
}
50+
}

src/JsonSchema/Constraints/Drafts/Draft2019/Draft2019Constraint.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = n
4242
$this->checkForKeyword('not', $value, $schema, $path, $i);
4343
$this->checkForKeyword('dependencies', $value, $schema, $path, $i);
4444
$this->checkForKeyword('dependentSchemas', $value, $schema, $path, $i);
45+
$this->checkForKeyword('dependentRequired', $value, $schema, $path, $i);
4546
$this->checkForKeyword('allOf', $value, $schema, $path, $i);
4647
$this->checkForKeyword('anyOf', $value, $schema, $path, $i);
4748
$this->checkForKeyword('oneOf', $value, $schema, $path, $i);

src/JsonSchema/Constraints/Drafts/Draft2019/Factory.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ class Factory extends \JsonSchema\Constraints\Factory
1515
'additionalItems' => AdditionalItemsConstraint::class,
1616
'dependencies' => DependenciesConstraint::class,
1717
'dependentSchemas' => DependentSchemasConstraint::class,
18+
'dependentRequired' => DependentRequiredConstraint::class,
1819
'type' => TypeConstraint::class,
1920
'const' => ConstConstraint::class,
2021
'enum' => EnumConstraint::class,

0 commit comments

Comments
 (0)