Skip to content

Commit ba4d621

Browse files
committed
feat: Add requireAll
1 parent 1ef0707 commit ba4d621

2 files changed

Lines changed: 53 additions & 0 deletions

File tree

src/Types/Concerns/HasProperties.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,18 @@ public function hasRequiredProperties(): bool
248248
return $this->requiredProperties !== [];
249249
}
250250

251+
/**
252+
* Convenience method to mark all properties as required.
253+
*/
254+
public function requireAll(): static
255+
{
256+
foreach ($this->properties as $property) {
257+
$property->required();
258+
}
259+
260+
return $this;
261+
}
262+
251263
/**
252264
* Add properties to schema array
253265
*

tests/Unit/Types/ObjectSchemaTest.php

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -547,3 +547,44 @@
547547
->and($objectWithoutRequired->hasRequiredProperties())->toBeFalse()
548548
->and($emptyObject->hasRequiredProperties())->toBeFalse();
549549
});
550+
551+
it('can mark all properties as required with requireAll method', function (): void {
552+
$objectSchema = Schema::object('user')
553+
->properties(
554+
Schema::string('name'),
555+
Schema::integer('age'),
556+
Schema::string('email'),
557+
)
558+
->requireAll();
559+
560+
$schemaArray = $objectSchema->toArray();
561+
562+
expect($schemaArray)->toHaveKey('required', ['name', 'age', 'email'])
563+
->and($objectSchema->getRequiredProperties())->toHaveCount(3)
564+
->and($objectSchema->getRequiredProperties())->toContain('name')
565+
->and($objectSchema->getRequiredProperties())->toContain('age')
566+
->and($objectSchema->getRequiredProperties())->toContain('email');
567+
568+
// Validation test - all properties are now required
569+
expect(fn() => $objectSchema->validate([
570+
'name' => 'John Doe',
571+
'age' => 30,
572+
]))->toThrow(
573+
SchemaException::class,
574+
'The required properties (email) are missing',
575+
);
576+
577+
expect(fn() => $objectSchema->validate([
578+
'name' => 'John Doe',
579+
'email' => 'john@example.com',
580+
]))->toThrow(
581+
SchemaException::class,
582+
'The required properties (age) are missing',
583+
);
584+
585+
expect(fn() => $objectSchema->validate([
586+
'name' => 'John Doe',
587+
'age' => 30,
588+
'email' => 'john@example.com',
589+
]))->not->toThrow(SchemaException::class);
590+
});

0 commit comments

Comments
 (0)