Skip to content

Commit 2885359

Browse files
committed
Support adding schema validation
To support the '$jsonSchema' operation on collections
1 parent ea742b8 commit 2885359

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/Schema/Blueprint.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,15 @@ public function hasIndex($indexOrColumns = null)
117117
return false;
118118
}
119119

120+
public function jsonSchema(array $schema = []): void
121+
{
122+
$this->connection->getDatabase()->modifyCollection($this->collection->getCollectionName(), [
123+
'validator' => [
124+
'$jsonSchema' => $schema,
125+
],
126+
]);
127+
}
128+
120129
/**
121130
* @param string|array $indexOrColumns
122131
*

tests/SchemaTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,34 @@ public function testCreateWithOptions(): void
6363
$this->assertEquals(1024, $collection['options']['size']);
6464
}
6565

66+
public function testCreateWithSchemaValidator(): void
67+
{
68+
$schema = [
69+
'bsonType' => 'object',
70+
'required' => [ 'username' ],
71+
'properties' => [
72+
'username' => [
73+
'bsonType' => 'string',
74+
'description' => 'must be a string and is required',
75+
],
76+
],
77+
];
78+
79+
Schema::create(self::COLL_2, function (Blueprint $collection) use ($schema) {
80+
$collection->string('username');
81+
$collection->jsonSchema($schema);
82+
});
83+
84+
$this->assertTrue(Schema::hasCollection(self::COLL_2));
85+
$this->assertTrue(Schema::hasTable(self::COLL_2));
86+
87+
$collection = Schema::getCollection(self::COLL_2);
88+
$this->assertEquals(
89+
['$jsonSchema' => $schema],
90+
$collection['options']['validator'],
91+
);
92+
}
93+
6694
public function testDrop(): void
6795
{
6896
Schema::create(self::COLL_1);

0 commit comments

Comments
 (0)