Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSON Schema Validation #2238

Merged
merged 1 commit into from
May 26, 2021
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
125 changes: 124 additions & 1 deletion docs/en/cookbook/validation-of-documents.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
Validation of Documents
=======================

Validation of Documents - Application Side
------------------------------------------

.. sectionauthor:: Benjamin Eberlei <kontakt@beberlei.de>

Doctrine does not ship with any internal validators, the reason
Expand Down Expand Up @@ -127,4 +130,124 @@ instances. This was already discussed in the previous blog post on
the Versionable extension, which requires another type of event
called "onFlush".

Further readings: :doc:`Lifecycle Events <../reference/events>`
Further readings: :doc:`Lifecycle Events <../reference/events>`

Validation of Documents - Database Side
---------------------------------------

.. sectionauthor:: Alexandre Abrioux <alexandre-abrioux@users.noreply.github.com>

.. note::

This feature has been introduced in version 2.3.0

MongoDB ≥ 3.6 offers the capability to validate documents during
insertions and updates through a schema associated to the collection
(cf. `MongoDB documentation <https://docs.mongodb.com/manual/core/schema-validation/>`_).

Doctrine MongoDB ODM now provides a way to take advantage of this functionality
thanks to the new :doc:`@Validation <../reference/annotations-reference#validation>`
annotation and its properties (also available with XML mapping):

-
``validator`` - The schema that will be used to validate documents.
It is a string representing a BSON document under the
`Extended JSON specification <https://github.com/mongodb/specifications/blob/master/source/extended-json.rst>`_.
-
``action`` - The behavior followed by MongoDB to handle documents that
violate the validation rules.
-
``level`` - The threshold used by MongoDB to filter operations that
will get validated.

Once defined, those options will be added to the collection after running
the ``odm:schema:create`` or ``odm:schema:update`` command.

.. configuration-block::

.. code-block:: php

<?php

namespace Documents;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;

/**
* @ODM\Document
* @ODM\Validation(
* validator=SchemaValidated::VALIDATOR,
* action=ClassMetadata::SCHEMA_VALIDATION_ACTION_WARN,
* level=ClassMetadata::SCHEMA_VALIDATION_LEVEL_MODERATE,
* )
*/
class SchemaValidated
{
public const VALIDATOR = <<<'EOT'
{
"$jsonSchema": {
"required": ["name"],
"properties": {
"name": {
"bsonType": "string",
"description": "must be a string and is required"
}
}
},
"$or": [
{ "phone": { "$type": "string" } },
{ "email": { "$regex": { "$regularExpression" : { "pattern": "@mongodb\\.com$", "options": "" } } } },
{ "status": { "$in": [ "Unknown", "Incomplete" ] } }
]
}
EOT;

/** @ODM\Id */
private $id;

/** @ODM\Field(type="string") */
private $name;

/** @ODM\Field(type="string") */
private $phone;

/** @ODM\Field(type="string") */
private $email;

/** @ODM\Field(type="string") */
private $status;
}

.. code-block:: xml

<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">

<document name="SchemaValidated">
<schema-validation action="warn" level="moderate">
{
"$jsonSchema": {
"required": ["name"],
"properties": {
"name": {
"bsonType": "string",
"description": "must be a string and is required"
}
}
},
"$or": [
{ "phone": { "$type": "string" } },
{ "email": { "$regex": { "$regularExpression" : { "pattern": "@mongodb\\.com$", "options": "" } } } },
{ "status": { "$in": [ "Unknown", "Incomplete" ] } }
]
}
</schema-validation>
</document>
</doctrine-mongo-mapping>

Please refer to the :doc:`@Validation <../reference/annotations-reference#document>` annotation reference
for more details on how to use this feature.
96 changes: 95 additions & 1 deletion docs/en/reference/annotations-reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ and it does not contain the class name of the persisted document, a
@Document
---------

Required annotation to mark a PHP class as a document, whose peristence will be
Required annotation to mark a PHP class as a document, whose persistence will be
managed by ODM.

Optional attributes:
Expand Down Expand Up @@ -1092,6 +1092,100 @@ Alias of `@Index`_, with the ``unique`` option set by default.

.. _annotations_reference_version:

@Validation
-----------

This annotation may be used at the class level to specify the validation schema
for the related collection.

-
``validator`` - Specifies a schema that will be used by
MongoDB to validate data inserted or updated in the collection.
Please refer to the following
`MongoDB documentation (Schema Validation ¶) <https://docs.mongodb.com/manual/core/schema-validation/>`_
for more details. The value should be a string representing a BSON document under the
`Extended JSON specification <https://github.com/mongodb/specifications/blob/master/source/extended-json.rst>`_.
The recommended way to fill up this property is to create a class constant
(eg. ``::VALIDATOR``) using the
`HEREDOC/NOWDOC syntax <https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc>`_
for clarity and to reference it as the annotation value.
Please note that if you decide to insert the schema directly in the annotation without
using a class constant then double quotes ``"`` have to be escaped by doubling them ``""``.
This method also requires that you don't prefix multiline strings by the Docblock asterisk symbol ``*``.
-
``action`` - Determines how MongoDB handles documents that violate
the validation rules. Please refer to the related
`MongoDB documentation (Accept or Reject Invalid Documents ¶) <https://docs.mongodb.com/manual/core/schema-validation/#accept-or-reject-invalid-documents>`_
for more details. The allowed values are the following:

- ``error``
- ``warn``

If it is not defined then the default behavior (``error``) will be used.
Those values are also declared as constants for convenience:

- ``\Doctrine\ODM\MongoDB\Mapping\ClassMetadata::SCHEMA_VALIDATION_ACTION_ERROR``
- ``\Doctrine\ODM\MongoDB\Mapping\ClassMetadata::SCHEMA_VALIDATION_ACTION_WARN``

Import the ``ClassMetadata`` namespace to use those constants in your annotation.
-
``level`` - Determines which operations MongoDB applies the
validation rules. Please refer to the related
`MongoDB documentation (Existing Documents ¶) <https://docs.mongodb.com/manual/core/schema-validation/#existing-documents>`_
for more details. The allowed values are the following:

- ``off``
- ``strict``
- ``moderate``

If it is not defined then the default behavior (``strict``) will be used.
Those values are also declared as constants for convenience:

- ``\Doctrine\ODM\MongoDB\Mapping\ClassMetadata::SCHEMA_VALIDATION_LEVEL_OFF``
- ``\Doctrine\ODM\MongoDB\Mapping\ClassMetadata::SCHEMA_VALIDATION_LEVEL_STRICT``
- ``\Doctrine\ODM\MongoDB\Mapping\ClassMetadata::SCHEMA_VALIDATION_LEVEL_MODERATE``

Import the ``ClassMetadata`` namespace to use those constants in your annotation.

.. code-block:: php

<?php

use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
// ... other imports

/**
* @Document
* @Validation(
* validator=SchemaValidated::VALIDATOR,
* action=ClassMetadata::SCHEMA_VALIDATION_ACTION_WARN,
* level=ClassMetadata::SCHEMA_VALIDATION_LEVEL_MODERATE,
* )
*/
class SchemaValidated
{
public const VALIDATOR = <<<'EOT'
{
"$jsonSchema": {
"required": ["name"],
"properties": {
"name": {
"bsonType": "string",
"description": "must be a string and is required"
}
}
},
"$or": [
{ "phone": { "$type": "string" } },
{ "email": { "$regex": { "$regularExpression" : { "pattern": "@mongodb\\.com$", "options": "" } } } },
{ "status": { "$in": [ "Unknown", "Incomplete" ] } }
]
}
EOT;

// rest of the class code...
}

@Version
--------

Expand Down
26 changes: 26 additions & 0 deletions doctrine-mongo-mapping.xsd
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@
<xs:element name="indexes" type="odm:indexes" minOccurs="0" />
<xs:element name="shard-key" type="odm:shard-key" minOccurs="0" />
<xs:element name="read-preference" type="odm:read-preference" minOccurs="0" />
<xs:element name="schema-validation" type="odm:schema-validation" minOccurs="0" />
</xs:choice>

<xs:attribute name="db" type="xs:NMTOKEN" />
Expand Down Expand Up @@ -514,4 +515,29 @@
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="value" type="xs:string" use="required" />
</xs:complexType>

<xs:complexType name="schema-validation">
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="action" type="odm:schema-validation-action" />
<xs:attribute name="level" type="odm:schema-validation-level" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>

<xs:simpleType name="schema-validation-action">
<xs:restriction base="xs:token">
<xs:enumeration value="error" />
<xs:enumeration value="warn" />
</xs:restriction>
</xs:simpleType>

<xs:simpleType name="schema-validation-level">
<xs:restriction base="xs:token">
<xs:enumeration value="off" />
<xs:enumeration value="strict" />
<xs:enumeration value="moderate" />
</xs:restriction>
</xs:simpleType>

</xs:schema>
34 changes: 34 additions & 0 deletions lib/Doctrine/ODM/MongoDB/Mapping/Annotations/Validation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

declare(strict_types=1);

namespace Doctrine\ODM\MongoDB\Mapping\Annotations;

/**
* @Annotation
* @Target({"CLASS"})
*/
class Validation
{
/** @var string */
public $validator;

/**
* @var string
* @Enum({
* \Doctrine\ODM\MongoDB\Mapping\ClassMetadata::SCHEMA_VALIDATION_ACTION_ERROR,
alexandre-abrioux marked this conversation as resolved.
Show resolved Hide resolved
* \Doctrine\ODM\MongoDB\Mapping\ClassMetadata::SCHEMA_VALIDATION_ACTION_WARN,
* })
*/
public $action;

/**
* @var string
* @Enum({
* \Doctrine\ODM\MongoDB\Mapping\ClassMetadata::SCHEMA_VALIDATION_LEVEL_OFF,
* \Doctrine\ODM\MongoDB\Mapping\ClassMetadata::SCHEMA_VALIDATION_LEVEL_STRICT,
* \Doctrine\ODM\MongoDB\Mapping\ClassMetadata::SCHEMA_VALIDATION_LEVEL_MODERATE,
* })
*/
public $level;
}
Loading