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

ReferenceMany: insert an empty array #2547

Merged
merged 1 commit into from
Oct 25, 2023
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
49 changes: 44 additions & 5 deletions docs/en/reference/embedded-mapping.rst
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ Embed a single document:
{
/** @Field(type="string") */
private $street;

// ...
}

Expand All @@ -47,7 +47,7 @@ Embed a single document:
<document name="Documents\User">
<embed-one field="address" target-document="Address" />
</document>

<embedded-document name="Address">
<field name="street" type="string" />
</embedded-document>
Expand Down Expand Up @@ -88,7 +88,7 @@ Embed many documents:
{
/** @Field(type="string") */
private $number;

// ...
}

Expand All @@ -102,7 +102,7 @@ Embed many documents:
<document name="Documents\User">
<embed-many field="phoneNumbers" target-document="PhoneNumber" />
</document>

<embedded-document name="PhoneNumber">
<field name="number" type="string" />
</embedded-document>
Expand Down Expand Up @@ -167,7 +167,7 @@ the embedded document. The field name can be customized with the
private $tasks;

// ...
public function __construct()
public function __construct()
{
$this->tasks = new ArrayCollection();
}
Expand Down Expand Up @@ -269,3 +269,42 @@ document and cannot exist without those by nature.

.. |FQCN| raw:: html
<abbr title="Fully-Qualified Class Name">FQCN</abbr>

.. _embed_store_empty_array:

Storing Empty Arrays in Embedded Documents
-------------------------------------------

By default, when an embedded collection property is empty, Doctrine does not store any data for it in the database.
However, in some cases, you may want to explicitly store an empty array for such properties.
You can achieve this behavior by using the `storeEmptyArray` option for embedded collections.

.. configuration-block::

.. code-block:: php
<?php
/** @Document */
class User
{
// ...
/**
* @EmbedMany(targetDocument=PhoneNumber::class, storeEmptyArray=true)
*/
private $phoneNumbers = [];
// ...
}
.. 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="Documents\User">
<embed-many field="phoneNumbers" target-document="PhoneNumber" store-empty-array="true" />
</document>
<embedded-document name="PhoneNumber">
<field name="number" type="string" />
</embedded-document>
</doctrine-mongo-mapping>
Now, when the `$phoneNumbers` collection is empty, an empty array will be stored in the database for the `User`
document's embedded `phoneNumbers` collection, even if there are no actual embedded documents in the collection.
36 changes: 36 additions & 0 deletions docs/en/reference/reference-mapping.rst
Original file line number Diff line number Diff line change
Expand Up @@ -434,3 +434,39 @@ from the database.
.. _`DBRef`: https://docs.mongodb.com/manual/reference/database-references/#dbrefs
.. |FQCN| raw:: html
<abbr title="Fully-Qualified Class Name">FQCN</abbr>

.. _store_empty_array:

Storing Empty Arrays
---------------------

By default, when a collection property is empty, Doctrine does not store any data for it in the database.
However, in some cases, you may want to explicitly store an empty array for such properties.
You can achieve this behavior by using the `storeEmptyArray` option.

.. configuration-block::

.. code-block:: php
<?php
/** @Document */
class User
{
// ...
/**
* @ReferenceMany(targetDocument=Account::class, storeEmptyArray=true)
*/
private $accounts = [];
// ...
}
.. 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="Documents\User">
<reference-many field="accounts" target-document="Documents\Account" store-empty-array="true" />
</document>
</doctrine-mongo-mapping>
Now, when the `$accounts` collection is empty, an empty array will be stored in the database for the `User` document,
even if there are no actual referenced documents.
2 changes: 2 additions & 0 deletions doctrine-mongo-mapping.xsd
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@
<xs:attribute name="strategy" type="odm:storage-strategy" default="pushAll" />
<xs:attribute name="not-saved" type="xs:boolean" />
<xs:attribute name="nullable" type="xs:boolean" />
<xs:attribute name="store-empty-array" type="xs:boolean" />
<xs:attribute name="also-load" type="xs:NMTOKEN" />
</xs:complexType>

Expand Down Expand Up @@ -293,6 +294,7 @@
<xs:attribute name="orphan-removal" type="xs:boolean" />
<xs:attribute name="not-saved" type="xs:boolean" />
<xs:attribute name="nullable" type="xs:boolean" />
<xs:attribute name="store-empty-array" type="xs:boolean" />
<xs:attribute name="also-load" type="xs:NMTOKEN" />
</xs:complexType>

Expand Down
5 changes: 5 additions & 0 deletions lib/Doctrine/ODM/MongoDB/Mapping/Annotations/EmbedMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ final class EmbedMany extends AbstractField
/** @var string|null */
public $collectionClass;

/** @var bool */
public $storeEmptyArray;

/** @param array<string, class-string>|null $discriminatorMap */
public function __construct(
?string $name = null,
Expand All @@ -48,6 +51,7 @@ public function __construct(
?array $discriminatorMap = null,
?string $defaultDiscriminatorValue = null,
?string $collectionClass = null,
bool $storeEmptyArray = false,
) {
parent::__construct($name, ClassMetadata::MANY, $nullable, $options, $strategy, $notSaved);

Expand All @@ -56,5 +60,6 @@ public function __construct(
$this->discriminatorMap = $discriminatorMap;
$this->defaultDiscriminatorValue = $defaultDiscriminatorValue;
$this->collectionClass = $collectionClass;
$this->storeEmptyArray = $storeEmptyArray;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ final class ReferenceMany extends AbstractField
/** @var string[] */
public $prime;

/** @var bool */
public $storeEmptyArray;

/**
* @param array<string, class-string>|null $discriminatorMap
* @param string[]|string|null $cascade
Expand Down Expand Up @@ -95,6 +98,7 @@ public function __construct(
?int $skip = null,
?string $collectionClass = null,
array $prime = [],
bool $storeEmptyArray = false,
) {
parent::__construct($name, ClassMetadata::MANY, $nullable, $options, $strategy, $notSaved);

Expand All @@ -113,5 +117,6 @@ public function __construct(
$this->skip = $skip;
$this->collectionClass = $collectionClass;
$this->prime = $prime;
$this->storeEmptyArray = $storeEmptyArray;
}
}
2 changes: 2 additions & 0 deletions lib/Doctrine/ODM/MongoDB/Mapping/ClassMetadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@
* criteria?: array<string, string>,
* alsoLoadFields?: list<string>,
* enumType?: class-string<BackedEnum>,
* storeEmptyArray?: bool,
* }
* @psalm-type AssociationFieldMapping = array{
* type?: string,
Expand Down Expand Up @@ -195,6 +196,7 @@
* index?: bool,
* criteria?: array<string, string>,
* alsoLoadFields?: list<string>,
* storeEmptyArray?: bool,
* }
* @psalm-type IndexKeys = array<string, mixed>
* @psalm-type IndexOptions = array{
Expand Down
1 change: 1 addition & 0 deletions lib/Doctrine/ODM/MongoDB/Mapping/Driver/XmlDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,7 @@ private function addReferenceMapping(ClassMetadata $class, ?SimpleXMLElement $re
'skip' => isset($attributes['skip']) ? (int) $attributes['skip'] : null,
'prime' => [],
'nullable' => isset($attributes['nullable']) ? ((string) $attributes['nullable'] === 'true') : false,
'storeEmptyArray' => isset($attributes['store-empty-array']) ? ((string) $attributes['store-empty-array'] === 'true') : false,
khaperets marked this conversation as resolved.
Show resolved Hide resolved
];

if (isset($attributes['field-name'])) {
Expand Down
24 changes: 20 additions & 4 deletions lib/Doctrine/ODM/MongoDB/Persisters/CollectionPersister.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public function __construct(private DocumentManager $dm, private PersistenceBuil
*/
public function delete(object $parent, array $collections, array $options): void
{
$unsetPathsMap = [];
$unsetPathsMap = $storeEmptyArray = [];

foreach ($collections as $collection) {
$mapping = $collection->getMapping();
Expand All @@ -67,19 +67,35 @@ public function delete(object $parent, array $collections, array $options): void
throw new UnexpectedValueException($mapping['strategy'] . ' delete collection strategy should have been handled by DocumentPersister. Please report a bug in issue tracker');
}

[$propertyPath] = $this->getPathAndParent($collection);
[$propertyPath] = $this->getPathAndParent($collection);

if ($mapping['storeEmptyArray']) {
$storeEmptyArray[$propertyPath] = [];

continue;
}

$unsetPathsMap[$propertyPath] = true;
}

if (empty($unsetPathsMap)) {
if (empty($unsetPathsMap) && empty($storeEmptyArray)) {
return;
}

/** @var string[] $unsetPaths */
$unsetPaths = array_keys($unsetPathsMap);

$query = [];
$unsetPaths = array_fill_keys($this->excludeSubPaths($unsetPaths), true);
$query = ['$unset' => $unsetPaths];

if ($unsetPathsMap) {
$query['$unset'] = $unsetPaths;
}

if ($storeEmptyArray) {
$query['$set'] = $storeEmptyArray;
}

$this->executeQuery($parent, $query, $options);
}

Expand Down
3 changes: 2 additions & 1 deletion lib/Doctrine/ODM/MongoDB/Persisters/PersistenceBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,8 @@ public function prepareInsertData($document)
// of duplicated entries stored in the collection
} elseif (
$mapping['type'] === ClassMetadata::MANY && ! $mapping['isInverseSide']
&& $mapping['strategy'] !== ClassMetadata::STORAGE_STRATEGY_ADD_TO_SET && ! $new->isEmpty()
&& (! $new->isEmpty() || $mapping['storeEmptyArray'])
&& ($mapping['strategy'] !== ClassMetadata::STORAGE_STRATEGY_ADD_TO_SET || $mapping['storeEmptyArray'])
) {
$insertData[$mapping['name']] = $this->prepareAssociatedCollectionValue($new, true);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,17 @@ public function testDeleteReferenceMany(): void
self::assertArrayNotHasKey('categories', $user, 'Test that the categories field was deleted');
}

public function testDeleteReferenceManyWithStoreEmptyArray(): void
{
$persister = $this->getCollectionPersister();
$user = $this->getTestUser('jwage');
self::assertInstanceOf(PersistentCollectionInterface::class, $user->roles);
$persister->delete($user, [$user->roles], []);

$user = $this->dm->getDocumentCollection(CollectionPersisterUser::class)->findOne(['username' => 'jwage']);
self::assertSame([], $user['roles'], 'Test that the roles field was stored as empty array');
}

public function testDeleteEmbedMany(): void
{
$persister = $this->getCollectionPersister();
Expand All @@ -54,6 +65,17 @@ public function testDeleteEmbedMany(): void
self::assertArrayNotHasKey('phonenumbers', $user, 'Test that the phonenumbers field was deleted');
}

public function testDeleteEmbedManyWithStoreEmptyArray(): void
{
$persister = $this->getCollectionPersister();
$user = $this->getTestUser('jwage');
self::assertInstanceOf(PersistentCollectionInterface::class, $user->groups);
$persister->delete($user, [$user->groups], []);

$user = $this->dm->getDocumentCollection(CollectionPersisterUser::class)->findOne(['username' => 'jwage']);
self::assertSame([], $user['groups'], 'Test that the groups field was stored as empty array');
}

public function testDeleteNestedEmbedMany(): void
{
$persister = $this->getCollectionPersister();
Expand Down Expand Up @@ -588,12 +610,26 @@ class CollectionPersisterUser
*/
public $categories = [];

/**
* @ODM\EmbedMany(targetDocument=CollectionPersisterGroup::class, storeEmptyArray=true)
*
* @var Collection<int, CollectionPersisterGroup>|array<CollectionPersisterGroup>
*/
public $groups = [];

/**
* @ODM\ReferenceMany(targetDocument=CollectionPersisterPhonenumber::class, cascade={"persist"})
*
* @var Collection<int, CollectionPersisterPhonenumber>|array<CollectionPersisterPhonenumber>
*/
public $phonenumbers = [];

/**
* @ODM\ReferenceMany(targetDocument=CollectionPersisterRole::class, cascade={"persist"}, storeEmptyArray=true)
*
* @var Collection<int, CollectionPersisterRole>|array<CollectionPersisterRole>
*/
public $roles = [];
}

/** @ODM\EmbeddedDocument */
Expand Down Expand Up @@ -642,6 +678,52 @@ public function __construct(string $phonenumber)
}
}

/** @ODM\Document(collection="role_collection_persister_test") */
class CollectionPersisterRole
{
/**
* @ODM\Id
*
* @var string|null
*/
public $id;

/**
* @ODM\Field(type="string")
*
* @var string
*/
public $role;

public function __construct(string $role)
{
$this->role = $role;
}
}

/** @ODM\Document(collection="group_collection_persister_test") */
class CollectionPersisterGroup
{
/**
* @ODM\Id
*
* @var string|null
*/
public $id;

/**
* @ODM\Field(type="string")
*
* @var string
*/
public $group;

public function __construct(string $group)
{
$this->group = $group;
}
}

/** @ODM\Document(collection="post_collection_persister_test") */
class CollectionPersisterPost
{
Expand Down
Loading
Loading