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

CustomType conversion is not working in QueryBuilder Where expression #11698

Open
wants to merge 2 commits into
base: 2.20.x
Choose a base branch
from
Open
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
44 changes: 44 additions & 0 deletions tests/Tests/ORM/Functional/Ticket/EncryptedType/Credential.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

declare(strict_types=1);

namespace Doctrine\Tests\ORM\Functional\Ticket\EncryptedType;

use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Entity
*/
class Credential
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*
* @var int
*/
public $id;

/**
* @ORM\Column(type="string")
*
* @var string
*/
public $username;

/**
* @ORM\Column(type="encrypted")
*
* @var string
*/
public $password;

public function __construct(
string $username,
string $password
) {
$this->username = $username;
$this->password = $password;
}
}
118 changes: 118 additions & 0 deletions tests/Tests/ORM/Functional/Ticket/EncryptedType/EncryptedTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
<?php

declare(strict_types=1);

namespace Doctrine\Tests\ORM\Functional\Ticket\EncryptedType;

use Doctrine\DBAL\Types\Type;
use Doctrine\ORM\Query;
use Doctrine\Tests\OrmFunctionalTestCase;

use function implode;
use function sprintf;
use function str_replace;

final class EncryptedTest extends OrmFunctionalTestCase
{
private const PASSWORD = '#password#';

public function setUp(): void
{
parent::setUp();

if (! Type::hasType(EncryptedType::NAME)) {
Type::addType(EncryptedType::NAME, EncryptedType::class);
}

$this->setUpEntitySchema([
Credential::class,
]);

$this->_em->getConfiguration()->setDefaultQueryHint(Query::HINT_CUSTOM_OUTPUT_WALKER, FixSqlWalker::class);
}

private function prepareData(): void
{
$credential = new Credential('root', self::PASSWORD);

$this->_em->persist($credential);
$this->_em->flush();
$this->_em->clear();
}

public function testUseQueryBuilderWhereExpression(): void
{
$this->prepareData();

$credential = $this->_em->createQueryBuilder()
->select('credential')
->from(Credential::class, 'credential')
->where('credential.password = :password')
->setParameter('password', self::PASSWORD)
->getQuery()
->getOneOrNullResult();

self::assertInstanceOf(Credential::class, $credential, $this->generateMessage('object not found'));
}

public function testUseQueryBuilderSubSelect(): void
{
$this->prepareData();

$subSelect = $this->_em->createQueryBuilder()
->select('credential.password')
->from(Credential::class, 'credential')
->where('credential.password = :password');

$password = $this->_em->createQueryBuilder()
->addSelect(sprintf('(%s)', $subSelect))
->from(Credential::class, 'c')
->setParameter('password', self::PASSWORD)
->setMaxResults(1)
->getQuery()
->getSingleScalarResult();

self::assertEquals(self::PASSWORD, $password, $this->generateMessage('object not found'));
}

public function testUseQueryBuilderSubSelectWhere(): void
{
$this->prepareData();

$subSelect = $this->_em->createQueryBuilder()
->select('credential.id')
->from(Credential::class, 'credential')
->where('credential.password = :password');

$password = $this->_em->createQueryBuilder()
->select('c')
->from(Credential::class, 'c')
->where(sprintf('c.id in(%s)', $subSelect))
->setParameter('password', self::PASSWORD)
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();

self::assertInstanceOf(Credential::class, $password, $this->generateMessage('object not found'));
}

public function testUseCriteria(): void
{
$this->prepareData();

$credential = $this->_em->getRepository(Credential::class)->findOneBy(['password' => self::PASSWORD]);

self::assertInstanceOf(Credential::class, $credential, $this->generateMessage('object not found'));
}

private function generateMessage(string $message): string
{
$sqlTrace = [];
foreach ($this->getQueryLog()->queries as $key => $log) {
$sql = sprintf(str_replace('?', '"%s"', $log['sql']), ...($log['params'] ?? []));
$sqlTrace[] = sprintf('#%s %s', $key, str_replace("\n", '', $sql));
}

return sprintf("%s\nSQL Trace:\n\t%s", $message, implode("\n\t", $sqlTrace));
}
}
68 changes: 68 additions & 0 deletions tests/Tests/ORM/Functional/Ticket/EncryptedType/EncryptedType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php

declare(strict_types=1);

namespace Doctrine\Tests\ORM\Functional\Ticket\EncryptedType;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\MySQLPlatform;
use Doctrine\DBAL\Platforms\SqlitePlatform;
use Doctrine\DBAL\Types\BlobType;

use function sprintf;

final class EncryptedType extends BlobType
{
public const NAME = 'encrypted';

public function getName(): string
{
return self::NAME;
}

private function getSecret(): string
{
return 'secret_key';
}

public function convertToDatabaseValueSQL($sqlExpr, AbstractPlatform $platform): string
{
if ($platform instanceof MySQLPlatform) {
return sprintf('AES_ENCRYPT(%s, \'%s\')', $sqlExpr, $this->getSecret());
}

if ($platform instanceof SqlitePlatform) {
return sprintf('CONCAT(%s, \'%s\')', $sqlExpr, $this->getSecret());
}

return $sqlExpr;
}

public function convertToPHPValueSQL($sqlExpr, $platform): string
{
if ($platform instanceof MySQLPlatform) {
return sprintf('AES_DECRYPT(%s, \'%s\')', $sqlExpr, $this->getSecret());
}

if ($platform instanceof SqlitePlatform) {
return sprintf('REPLACE(%s, \'%s\', \'\')', $sqlExpr, $this->getSecret());
}

return $sqlExpr;
}

public function convertToPHPValue($value, AbstractPlatform $platform): string
{
return $value;
}

public function requiresSQLCommentHint(AbstractPlatform $platform): bool
{
return true;
}

public function canRequireSQLConversion(): bool
{
return true;
}
}
31 changes: 31 additions & 0 deletions tests/Tests/ORM/Functional/Ticket/EncryptedType/FixSqlWalker.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

declare(strict_types=1);

namespace Doctrine\Tests\ORM\Functional\Ticket\EncryptedType;

use Doctrine\DBAL\Types\Type;
use Doctrine\ORM\Query\AST\PathExpression;
use Doctrine\ORM\Query\SqlWalker;

final class FixSqlWalker extends SqlWalker
{
public function walkPathExpression($pathExpr): string
{
$sql = parent::walkPathExpression($pathExpr);

if ($pathExpr->type === PathExpression::TYPE_STATE_FIELD) {
$fieldName = $pathExpr->field;
$dqlAlias = $pathExpr->identificationVariable;
$class = $this->getMetadataForDqlAlias($dqlAlias);
$fieldMapping = $class->fieldMappings[$fieldName] ?? [];

if (isset($fieldMapping['requireSQLConversion'])) {
$type = Type::getType($fieldMapping['type']);
$sql = $type->convertToPHPValueSQL($sql, $this->getConnection()->getDatabasePlatform());
}
}

return $sql;
}
}
Loading