Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/Schema/Blueprint.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use MongoDB\Laravel\Connection;

use function array_flip;
use function array_merge;
use function implode;
use function in_array;
use function is_array;
Expand Down Expand Up @@ -117,6 +118,24 @@ public function hasIndex($indexOrColumns = null)
return false;
}

public function jsonSchema(
array $schema = [],
?string $validationLevel = null,
?string $validationAction = null,
): void {
$options = array_merge(
[
'validator' => [
'$jsonSchema' => $schema,
],
],
$validationLevel ? ['validationLevel' => $validationLevel] : [],
$validationAction ? ['validationAction' => $validationAction] : [],
);

$this->connection->getDatabase()->modifyCollection($this->collection->getCollectionName(), $options);
}

/**
* @param string|array $indexOrColumns
*
Expand Down
33 changes: 33 additions & 0 deletions tests/SchemaTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,39 @@ public function testCreateWithOptions(): void
$this->assertEquals(1024, $collection['options']['size']);
}

public function testCreateWithSchemaValidator(): void
{
$schema = [
'bsonType' => 'object',
'required' => [ 'username' ],
'properties' => [
'username' => [
'bsonType' => 'string',
'description' => 'must be a string and is required',
],
],
];

Schema::create(self::COLL_2, function (Blueprint $collection) use ($schema) {
$collection->string('username');
$collection->jsonSchema(schema: $schema, validationAction: 'warn');
});

$this->assertTrue(Schema::hasCollection(self::COLL_2));
$this->assertTrue(Schema::hasTable(self::COLL_2));

$collection = Schema::getCollection(self::COLL_2);
$this->assertEquals(
['$jsonSchema' => $schema],
$collection['options']['validator'],
);

$this->assertEquals(
'warn',
$collection['options']['validationAction'],
);
}

public function testDrop(): void
{
Schema::create(self::COLL_1);
Expand Down
Loading