Skip to content

Commit

Permalink
Merge pull request #10775 from doctrine/2.15.x
Browse files Browse the repository at this point in the history
Merge 2.15.x up into 2.16.x
  • Loading branch information
greg0ire authored Jun 13, 2023
2 parents 5c74795 + 1adb5c0 commit 41f704c
Show file tree
Hide file tree
Showing 6 changed files with 160 additions and 4 deletions.
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,14 @@
"doctrine/annotations": "^1.13 || ^2",
"doctrine/coding-standard": "^9.0.2 || ^12.0",
"phpbench/phpbench": "^0.16.10 || ^1.0",
"phpstan/phpstan": "~1.4.10 || 1.10.14",
"phpstan/phpstan": "~1.4.10 || 1.10.18",
"phpunit/phpunit": "^7.5 || ^8.5 || ^9.6",
"psr/log": "^1 || ^2 || ^3",
"squizlabs/php_codesniffer": "3.7.2",
"symfony/cache": "^4.4 || ^5.4 || ^6.0",
"symfony/var-exporter": "^4.4 || ^5.4 || ^6.2",
"symfony/yaml": "^3.4 || ^4.0 || ^5.0 || ^6.0",
"vimeo/psalm": "4.30.0 || 5.11.0"
"vimeo/psalm": "4.30.0 || 5.12.0"
},
"conflict": {
"doctrine/annotations": "<1.13 || >= 3.0"
Expand Down
34 changes: 34 additions & 0 deletions docs/en/reference/native-sql.rst
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,40 @@ The first parameter is the name of the column in the SQL result set
and the second parameter is the result alias under which the value
of the column will be placed in the transformed Doctrine result.

Special case: DTOs
...................

You can also use ``ResultSetMapping`` to map the results of a native SQL
query to a DTO (Data Transfer Object). This is done by adding scalar
results for each argument of the DTO's constructor, then filling the
``newObjectMappings`` property of the ``ResultSetMapping`` with
information about where to map each scalar result:

.. code-block:: php
<?php
$rsm = new ResultSetMapping();
$rsm->addScalarResult('name', 1, 'string');
$rsm->addScalarResult('email', 2, 'string');
$rsm->addScalarResult('city', 3, 'string');
$rsm->newObjectMappings['name'] = [
'className' => CmsUserDTO::class,
'objIndex' => 0, // a result can contain many DTOs, this is the index of the DTO to map to
'argIndex' => 0, // each scalar result can be mapped to a different argument of the DTO constructor
];
$rsm->newObjectMappings['email'] = [
'className' => CmsUserDTO::class,
'objIndex' => 0,
'argIndex' => 1,
];
$rsm->newObjectMappings['city'] = [
'className' => CmsUserDTO::class,
'objIndex' => 0,
'argIndex' => 2,
];
Meta results
~~~~~~~~~~~~

Expand Down
13 changes: 12 additions & 1 deletion lib/Doctrine/ORM/Proxy/ProxyFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use ReflectionProperty;
use Symfony\Component\VarExporter\ProxyHelper;
use Symfony\Component\VarExporter\VarExporter;
use Throwable;

use function array_flip;
use function str_replace;
Expand Down Expand Up @@ -204,7 +205,17 @@ private function createInitializer(ClassMetadata $classMetadata, EntityPersister

$identifier = $classMetadata->getIdentifierValues($proxy);

if ($entityPersister->loadById($identifier, $proxy) === null) {
try {
$entity = $entityPersister->loadById($identifier, $proxy);
} catch (Throwable $exception) {
$proxy->__setInitializer($initializer);
$proxy->__setCloner($cloner);
$proxy->__setInitialized(false);

throw $exception;
}

if ($entity === null) {
$proxy->__setInitializer($initializer);
$proxy->__setCloner($cloner);
$proxy->__setInitialized(false);
Expand Down
13 changes: 12 additions & 1 deletion psalm-baseline.xml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<files psalm-version="5.11.0@c9b192ab8400fdaf04b2b13d110575adc879aa90">
<files psalm-version="5.12.0@f90118cdeacd0088e7215e64c0c99ceca819e176">
<file src="lib/Doctrine/ORM/AbstractQuery.php">
<DeprecatedClass>
<code>IterableResult</code>
Expand Down Expand Up @@ -213,6 +213,11 @@
<code>CacheProvider</code>
</MoreSpecificReturnType>
</file>
<file src="lib/Doctrine/ORM/Cache/Region/FileLockRegion.php">
<ArgumentTypeCoercion>
<code><![CDATA[sprintf('%s/*.%s', $this->directory, self::LOCK_EXTENSION)]]></code>
</ArgumentTypeCoercion>
</file>
<file src="lib/Doctrine/ORM/Cache/RegionsConfiguration.php">
<RedundantCastGivenDocblockType>
<code>(int) $defaultLifetime</code>
Expand Down Expand Up @@ -437,6 +442,9 @@
<ReferenceReusedFromConfusingScope>
<code>$baseElement</code>
</ReferenceReusedFromConfusingScope>
<UnsupportedPropertyReferenceUsage>
<code><![CDATA[$baseElement =& $this->resultPointers[$parent]]]></code>
</UnsupportedPropertyReferenceUsage>
<UnsupportedReferenceUsage>
<code><![CDATA[$baseElement =& $this->resultPointers[$parent][key($first)]]]></code>
<code><![CDATA[$this->resultPointers[$dqlAlias] =& $coll[key($coll)]]]></code>
Expand Down Expand Up @@ -2455,6 +2463,9 @@
</MissingTemplateParam>
</file>
<file src="lib/Doctrine/ORM/Tools/ConvertDoctrine1Schema.php">
<ArgumentTypeCoercion>
<code><![CDATA[$path . '/*.yml']]></code>
</ArgumentTypeCoercion>
<PossiblyUndefinedArrayOffset>
<code><![CDATA[$column['type']]]></code>
</PossiblyUndefinedArrayOffset>
Expand Down
72 changes: 72 additions & 0 deletions tests/Doctrine/Tests/ORM/Functional/NativeQueryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use Doctrine\Tests\Models\CMS\CmsEmail;
use Doctrine\Tests\Models\CMS\CmsPhonenumber;
use Doctrine\Tests\Models\CMS\CmsUser;
use Doctrine\Tests\Models\CMS\CmsUserDTO;
use Doctrine\Tests\Models\Company\CompanyContract;
use Doctrine\Tests\Models\Company\CompanyEmployee;
use Doctrine\Tests\Models\Company\CompanyFixContract;
Expand Down Expand Up @@ -155,6 +156,77 @@ public function testJoinedOneToManyNativeQuery(): void
self::assertSame($phones[0]->getUser(), $users[0]);
}

public function testMappingAsDto(): void
{
$user = new CmsUser();
$user->name = 'Roman';
$user->username = 'romanb';
$user->status = 'dev';

$phone = new CmsPhonenumber();
$phone->phonenumber = 424242;

$user->addPhonenumber($phone);

$email = new CmsEmail();
$email->email = 'fabio.bat.silva@gmail.com';

$user->setEmail($email);

$addr = new CmsAddress();
$addr->country = 'germany';
$addr->zip = 10827;
$addr->city = 'Berlin';

$user->setAddress($addr);

$this->_em->persist($user);
$this->_em->flush();

$this->_em->clear();

$rsm = new ResultSetMapping();
$rsm->addScalarResult('name', 1, 'string');
$rsm->addScalarResult('email', 2, 'string');
$rsm->addScalarResult('city', 3, 'string');
$rsm->newObjectMappings['name'] = [
'className' => CmsUserDTO::class,
'objIndex' => 0,
'argIndex' => 0,
];
$rsm->newObjectMappings['email'] = [
'className' => CmsUserDTO::class,
'objIndex' => 0,
'argIndex' => 1,
];
$rsm->newObjectMappings['city'] = [
'className' => CmsUserDTO::class,
'objIndex' => 0,
'argIndex' => 2,
];
$query = $this->_em->createNativeQuery(
<<<'SQL'
SELECT u.name, e.email, a.city
FROM cms_users u
INNER JOIN cms_phonenumbers p ON u.id = p.user_id
INNER JOIN cms_emails e ON e.id = u.email_id
INNER JOIN cms_addresses a ON u.id = a.user_id
WHERE username = ?
SQL
,
$rsm
);
$query->setParameter(1, 'romanb');

$users = $query->getResult();
self::assertCount(1, $users);
$user = $users[0];
self::assertInstanceOf(CmsUserDTO::class, $user);
self::assertEquals('Roman', $user->name);
self::assertEquals('fabio.bat.silva@gmail.com', $user->email);
self::assertEquals('Berlin', $user->address);
}

public function testJoinedOneToOneNativeQuery(): void
{
$user = new CmsUser();
Expand Down
28 changes: 28 additions & 0 deletions tests/Doctrine/Tests/ORM/Proxy/ProxyFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use Doctrine\Tests\Models\ECommerce\ECommerceFeature;
use Doctrine\Tests\OrmTestCase;
use Doctrine\Tests\PHPUnitCompatibility\MockBuilderCompatibilityTools;
use Exception;
use ReflectionProperty;
use stdClass;

Expand Down Expand Up @@ -145,6 +146,33 @@ public function testFailedProxyLoadingDoesNotMarkTheProxyAsInitialized(): void
self::assertFalse($proxy->__isInitialized());
}

public function testExceptionOnProxyLoadingDoesNotMarkTheProxyAsInitialized(): void
{
$persister = $this
->getMockBuilderWithOnlyMethods(BasicEntityPersister::class, ['load', 'getClassMetadata'])
->disableOriginalConstructor()
->getMock();
$this->uowMock->setEntityPersister(ECommerceFeature::class, $persister);

$proxy = $this->proxyFactory->getProxy(ECommerceFeature::class, ['id' => 42]);
assert($proxy instanceof Proxy);

$exception = new Exception('Literally any kind of connection exception');

$persister
->expects(self::atLeastOnce())
->method('load')
->will(self::throwException($exception));

try {
$proxy->getDescription();
self::fail('An exception was expected to be raised');
} catch (Exception $exception) {
}

self::assertFalse($proxy->__isInitialized(), 'The proxy should not be initialized');
}

/** @group DDC-2432 */
public function testFailedProxyCloningDoesNotMarkTheProxyAsInitialized(): void
{
Expand Down

0 comments on commit 41f704c

Please sign in to comment.