Skip to content

add capability to hydrate an entity in a dto #11847

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

Merged
merged 1 commit into from
Apr 22, 2025
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
23 changes: 17 additions & 6 deletions docs/en/reference/dql-doctrine-query-language.rst
Original file line number Diff line number Diff line change
Expand Up @@ -674,6 +674,16 @@ The ``NAMED`` keyword must precede all DTO you want to instantiate :
If two arguments have the same name, a ``DuplicateFieldException`` is thrown.
If a field cannot be matched with a property name, a ``NoMatchingPropertyException`` is thrown. This typically happens when using functions without aliasing them.

You can hydrate an entity nested in a DTO :

.. code-block:: php

<?php
$query = $em->createQuery('SELECT NEW CustomerDTO(c.name, a AS address) FROM Customer c JOIN c.address a');
$users = $query->getResult(); // array of CustomerDTO

// CustomerDTO => {name : 'DOE', email: null, address : {city: 'New York', zip: '10011', address: 'Abbey Road'}

Using INDEX BY
~~~~~~~~~~~~~~

Expand Down Expand Up @@ -1697,12 +1707,13 @@ Select Expressions

.. code-block:: php

SelectExpression ::= (IdentificationVariable | ScalarExpression | AggregateExpression | FunctionDeclaration | PartialObjectExpression | "(" Subselect ")" | CaseExpression | NewObjectExpression) [["AS"] ["HIDDEN"] AliasResultVariable]
SimpleSelectExpression ::= (StateFieldPathExpression | IdentificationVariable | FunctionDeclaration | AggregateExpression | "(" Subselect ")" | ScalarExpression) [["AS"] AliasResultVariable]
PartialObjectExpression ::= "PARTIAL" IdentificationVariable "." PartialFieldSet
PartialFieldSet ::= "{" SimpleStateField {"," SimpleStateField}* "}"
NewObjectExpression ::= "NEW" AbstractSchemaName "(" NewObjectArg {"," NewObjectArg}* ")"
NewObjectArg ::= (ScalarExpression | "(" Subselect ")" | NewObjectExpression) ["AS" AliasResultVariable]
SelectExpression ::= (IdentificationVariable | ScalarExpression | AggregateExpression | FunctionDeclaration | PartialObjectExpression | "(" Subselect ")" | CaseExpression | NewObjectExpression) [["AS"] ["HIDDEN"] AliasResultVariable]
SimpleSelectExpression ::= (StateFieldPathExpression | IdentificationVariable | FunctionDeclaration | AggregateExpression | "(" Subselect ")" | ScalarExpression) [["AS"] AliasResultVariable]
PartialObjectExpression ::= "PARTIAL" IdentificationVariable "." PartialFieldSet
PartialFieldSet ::= "{" SimpleStateField {"," SimpleStateField}* "}"
NewObjectExpression ::= "NEW" AbstractSchemaName "(" NewObjectArg {"," NewObjectArg}* ")"
NewObjectArg ::= (ScalarExpression | "(" Subselect ")" | NewObjectExpression | EntityAsDtoArgumentExpression) ["AS" AliasResultVariable]
EntityAsDtoArgumentExpression ::= IdentificationVariable

Conditional Expressions
~~~~~~~~~~~~~~~~~~~~~~~
Expand Down
6 changes: 0 additions & 6 deletions phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -2796,12 +2796,6 @@ parameters:
count: 1
path: src/Query/SqlWalker.php

-
message: '#^Property Doctrine\\ORM\\Query\\SqlWalker\:\:\$selectedClasses \(array\<string, array\{class\: Doctrine\\ORM\\Mapping\\ClassMetadata, dqlAlias\: string, resultAlias\: string\|null\}\>\) does not accept non\-empty\-array\<int\|string, array\{class\: Doctrine\\ORM\\Mapping\\ClassMetadata, dqlAlias\: mixed, resultAlias\: string\|null\}\>\.$#'
identifier: assign.propertyType
count: 1
path: src/Query/SqlWalker.php

-
message: '#^Property Doctrine\\ORM\\Query\\SqlWalker\:\:\$selectedClasses with generic class Doctrine\\ORM\\Mapping\\ClassMetadata does not specify its types\: T$#'
identifier: missingType.generics
Expand Down
22 changes: 22 additions & 0 deletions src/Internal/Hydration/AbstractHydrator.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use ReflectionClass;

use function array_key_exists;
use function array_keys;
use function array_map;
use function array_merge;
use function count;
Expand Down Expand Up @@ -348,14 +349,29 @@
}
}

$nestedEntities = [];
/**@var string $argAlias */
foreach ($this->resultSetMapping()->nestedNewObjectArguments as ['ownerIndex' => $ownerIndex, 'argIndex' => $argIndex, 'argAlias' => $argAlias]) {
if (array_key_exists($argAlias, $rowData['newObjects'])) {
ksort($rowData['newObjects'][$argAlias]['args']);
$rowData['newObjects'][$ownerIndex]['args'][$argIndex] = $rowData['newObjects'][$argAlias]['class']->newInstanceArgs($rowData['newObjects'][$argAlias]['args']);
unset($rowData['newObjects'][$argAlias]);
} elseif (array_key_exists($argAlias, $rowData['data'])) {
if (! array_key_exists($argAlias, $nestedEntities)) {
$nestedEntities[$argAlias] = '';
$rowData['data'][$argAlias] = $this->hydrateNestedEntity($rowData['data'][$argAlias], $argAlias);
}

$rowData['newObjects'][$ownerIndex]['args'][$argIndex] = $rowData['data'][$argAlias];
} else {
throw new LogicException($argAlias . ' does not exist');

Check warning on line 367 in src/Internal/Hydration/AbstractHydrator.php

View check run for this annotation

Codecov / codecov/patch

src/Internal/Hydration/AbstractHydrator.php#L367

Added line #L367 was not covered by tests
}
}

foreach (array_keys($nestedEntities) as $entity) {
unset($rowData['data'][$entity]);
}

foreach ($rowData['newObjects'] as $objIndex => $newObject) {
ksort($rowData['newObjects'][$objIndex]['args']);
$obj = $rowData['newObjects'][$objIndex]['class']->newInstanceArgs($rowData['newObjects'][$objIndex]['args']);
Expand All @@ -366,6 +382,12 @@
return $rowData;
}

/** @param mixed[] $data pre-hydrated SQL Result Row. */
protected function hydrateNestedEntity(array $data, string $dqlAlias): mixed

Check warning on line 386 in src/Internal/Hydration/AbstractHydrator.php

View check run for this annotation

Codecov / codecov/patch

src/Internal/Hydration/AbstractHydrator.php#L386

Added line #L386 was not covered by tests
{
return $data;

Check warning on line 388 in src/Internal/Hydration/AbstractHydrator.php

View check run for this annotation

Codecov / codecov/patch

src/Internal/Hydration/AbstractHydrator.php#L388

Added line #L388 was not covered by tests
}

/**
* Processes a row of the result set.
*
Expand Down
14 changes: 14 additions & 0 deletions src/Internal/Hydration/ObjectHydrator.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@
$parent = $this->resultSetMapping()->parentAliasMap[$dqlAlias];

if (! isset($this->resultSetMapping()->aliasMap[$parent])) {
if (isset($this->resultSetMapping()->nestedEntities[$dqlAlias])) {
continue;
}

throw HydrationException::parentObjectOfRelationNotFound($dqlAlias, $parent);
}

Expand Down Expand Up @@ -569,6 +573,16 @@
}
}

/** @param mixed[] $data pre-hydrated SQL Result Row. */
protected function hydrateNestedEntity(array $data, string $dqlAlias): mixed
{
if (isset($this->resultSetMapping()->nestedEntities[$dqlAlias])) {
return $this->getEntity($data, $dqlAlias);
}

return $data;

Check warning on line 583 in src/Internal/Hydration/ObjectHydrator.php

View check run for this annotation

Codecov / codecov/patch

src/Internal/Hydration/ObjectHydrator.php#L583

Added line #L583 was not covered by tests
}

/**
* When executed in a hydrate() loop we may have to clear internal state to
* decrease memory consumption.
Expand Down
26 changes: 26 additions & 0 deletions src/Query/AST/EntityAsDtoArgumentExpression.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace Doctrine\ORM\Query\AST;

use Doctrine\ORM\Query\SqlWalker;

/**
* EntityAsDtoArgumentExpression ::= IdentificationVariable
*
* @link www.doctrine-project.org
*/
class EntityAsDtoArgumentExpression extends Node
{
public function __construct(
public mixed $expression,
public string|null $identificationVariable,
) {
}

public function dispatch(SqlWalker $walker): string
{
return $walker->walkEntityAsDtoArgumentExpression($this);
}
}
46 changes: 46 additions & 0 deletions src/Query/Parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -1106,6 +1106,50 @@
return $this->PathExpression(AST\PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION);
}

/**
* EntityAsDtoArgumentExpression ::= IdentificationVariable
*/
public function EntityAsDtoArgumentExpression(): AST\EntityAsDtoArgumentExpression
{
assert($this->lexer->lookahead !== null);
$expression = null;
$identVariable = null;
$peek = $this->lexer->glimpse();
$lookaheadType = $this->lexer->lookahead->type;
assert($peek !== null);

assert($lookaheadType === TokenType::T_IDENTIFIER);
assert($peek->type !== TokenType::T_DOT);
assert($peek->type !== TokenType::T_OPEN_PARENTHESIS);

$expression = $identVariable = $this->IdentificationVariable();

// [["AS"] AliasResultVariable]
$mustHaveAliasResultVariable = false;

if ($this->lexer->isNextToken(TokenType::T_AS)) {
$this->match(TokenType::T_AS);

Check warning on line 1131 in src/Query/Parser.php

View check run for this annotation

Codecov / codecov/patch

src/Query/Parser.php#L1131

Added line #L1131 was not covered by tests

$mustHaveAliasResultVariable = true;

Check warning on line 1133 in src/Query/Parser.php

View check run for this annotation

Codecov / codecov/patch

src/Query/Parser.php#L1133

Added line #L1133 was not covered by tests
}

$aliasResultVariable = null;

if ($mustHaveAliasResultVariable || $this->lexer->isNextToken(TokenType::T_IDENTIFIER)) {
$token = $this->lexer->lookahead;
$aliasResultVariable = $this->AliasResultVariable();

Check warning on line 1140 in src/Query/Parser.php

View check run for this annotation

Codecov / codecov/patch

src/Query/Parser.php#L1139-L1140

Added lines #L1139 - L1140 were not covered by tests

// Include AliasResultVariable in query components.
$this->queryComponents[$aliasResultVariable] = [
'resultVariable' => $expression,
'nestingLevel' => $this->nestingLevel,
'token' => $token,
];

Check warning on line 1147 in src/Query/Parser.php

View check run for this annotation

Codecov / codecov/patch

src/Query/Parser.php#L1143-L1147

Added lines #L1143 - L1147 were not covered by tests
}

return new AST\EntityAsDtoArgumentExpression($expression, $identVariable);
}

/**
* SelectClause ::= "SELECT" ["DISTINCT"] SelectExpression {"," SelectExpression}
*/
Expand Down Expand Up @@ -1849,6 +1893,8 @@
$this->match(TokenType::T_CLOSE_PARENTHESIS);
} elseif ($token->type === TokenType::T_NEW) {
$expression = $this->NewObjectExpression();
} elseif ($token->type === TokenType::T_IDENTIFIER && $peek->type !== TokenType::T_DOT && $peek->type !== TokenType::T_OPEN_PARENTHESIS) {
$expression = $this->EntityAsDtoArgumentExpression();
} else {
$expression = $this->ScalarExpression();
}
Expand Down
9 changes: 8 additions & 1 deletion src/Query/ResultSetMapping.php
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ class ResultSetMapping
/**
* Maps last argument for new objects in order to initiate object construction
*
* @phpstan-var array<int|string, array{ownerIndex: string|int, argIndex: int|string}>
* @phpstan-var array<int|string, array{ownerIndex: string|int, argIndex: int|string, argAlias: string}>
*/
public array $nestedNewObjectArguments = [];

Expand All @@ -187,6 +187,13 @@ class ResultSetMapping
*/
public array $discriminatorParameters = [];

/**
* Entities nested in Dto's
*
* @phpstan-var array<string, array<string, (int|string)>>
*/
public array $nestedEntities = [];

/**
* Adds an entity result to this ResultSetMapping.
*
Expand Down
Loading