Skip to content

Properly format value in UniqueEntityValidator #20287

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
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
34 changes: 25 additions & 9 deletions src/Symfony/Bridge/Doctrine/Test/DoctrineTestHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
namespace Symfony\Bridge\Doctrine\Test;

use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Cache\ArrayCache;
use Doctrine\ORM\Configuration;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
use Doctrine\ORM\EntityManager;

Expand All @@ -25,22 +27,19 @@ class DoctrineTestHelper
/**
* Returns an entity manager for testing.
*
* @param Configuration|null $config
*
* @return EntityManager
*/
public static function createTestEntityManager()
public static function createTestEntityManager(Configuration $config = null)
{
if (!extension_loaded('pdo_sqlite')) {
\PHPUnit_Framework_TestCase::markTestSkipped('Extension pdo_sqlite is required.');
}

$config = new \Doctrine\ORM\Configuration();
$config->setEntityNamespaces(array('SymfonyTestsDoctrine' => 'Symfony\Bridge\Doctrine\Tests\Fixtures'));
$config->setAutoGenerateProxyClasses(true);
$config->setProxyDir(\sys_get_temp_dir());
$config->setProxyNamespace('SymfonyTests\Doctrine');
$config->setMetadataDriverImpl(new AnnotationDriver(new AnnotationReader()));
$config->setQueryCacheImpl(new \Doctrine\Common\Cache\ArrayCache());
$config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache());
if (null === $config) {
$config = self::createTestConfiguration();
}

$params = array(
'driver' => 'pdo_sqlite',
Expand All @@ -50,6 +49,23 @@ public static function createTestEntityManager()
return EntityManager::create($params, $config);
}

/**
* @return Configuration
*/
public static function createTestConfiguration()
{
$config = new Configuration();
$config->setEntityNamespaces(array('SymfonyTestsDoctrine' => 'Symfony\Bridge\Doctrine\Tests\Fixtures'));
$config->setAutoGenerateProxyClasses(true);
$config->setProxyDir(\sys_get_temp_dir());
$config->setProxyNamespace('SymfonyTests\Doctrine');
$config->setMetadataDriverImpl(new AnnotationDriver(new AnnotationReader()));
$config->setQueryCacheImpl(new ArrayCache());
$config->setMetadataCacheImpl(new ArrayCache());

return $config;
}

/**
* This class cannot be instantiated.
*/
Expand Down
85 changes: 85 additions & 0 deletions src/Symfony/Bridge/Doctrine/Test/TestRepositoryFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wrong license header :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Whoops ;)


namespace Symfony\Bridge\Doctrine\Test;

use Doctrine\Common\Persistence\ObjectRepository;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Repository\RepositoryFactory;

/**
* @author Andreas Braun <alcaeus@alcaeus.org>
*/
final class TestRepositoryFactory implements RepositoryFactory
{
/**
* The list of EntityRepository instances.
*
* @var ObjectRepository[]
*/
private $repositoryList = array();

/**
* {@inheritdoc}
*/
public function getRepository(EntityManagerInterface $entityManager, $entityName)
{
$repositoryHash = $this->getRepositoryHash($entityManager, $entityName);

if (isset($this->repositoryList[$repositoryHash])) {
return $this->repositoryList[$repositoryHash];
}

return $this->repositoryList[$repositoryHash] = $this->createRepository($entityManager, $entityName);
}

/**
* @param EntityManagerInterface $entityManager
* @param string $entityName
* @param ObjectRepository $repository
*/
public function setRepository(EntityManagerInterface $entityManager, $entityName, ObjectRepository $repository)
{
$repositoryHash = $this->getRepositoryHash($entityManager, $entityName);

$this->repositoryList[$repositoryHash] = $repository;
}

/**
* Create a new repository instance for an entity class.
*
* @param EntityManagerInterface $entityManager The EntityManager instance.
* @param string $entityName The name of the entity.
*
* @return ObjectRepository
*/
private function createRepository(EntityManagerInterface $entityManager, $entityName)
{
/* @var $metadata ClassMetadata */
$metadata = $entityManager->getClassMetadata($entityName);
$repositoryClassName = $metadata->customRepositoryClassName
?: $entityManager->getConfiguration()->getDefaultRepositoryClassName();

return new $repositoryClassName($entityManager, $metadata);
}

/**
* @param EntityManagerInterface $entityManager
* @param string $entityName
*
* @return string
*/
private function getRepositoryHash(EntityManagerInterface $entityManager, $entityName)
{
return $entityManager->getClassMetadata($entityName)->getName().spl_object_hash($entityManager);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ class SingleIntIdEntity
/** @Column(type="string", nullable=true) */
public $name;

/** @Column(type="array", nullable=true) */
public $phoneNumbers = array();

public function __construct($id, $name)
{
$this->id = $id;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\Persistence\ObjectRepository;
use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper;
use Symfony\Bridge\Doctrine\Test\TestRepositoryFactory;
use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity;
use Symfony\Bridge\Doctrine\Tests\Fixtures\DoubleNameEntity;
use Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity;
Expand Down Expand Up @@ -48,9 +49,16 @@ class UniqueEntityValidatorTest extends AbstractConstraintValidatorTest
*/
protected $repository;

protected $repositoryFactory;

protected function setUp()
{
$this->em = DoctrineTestHelper::createTestEntityManager();
$this->repositoryFactory = new TestRepositoryFactory();

$config = DoctrineTestHelper::createTestConfiguration();
$config->setRepositoryFactory($this->repositoryFactory);

$this->em = DoctrineTestHelper::createTestEntityManager($config);
$this->registry = $this->createRegistryMock($this->em);
$this->createSchema($this->em);

Expand Down Expand Up @@ -164,7 +172,7 @@ public function testValidateUniqueness()

$this->buildViolation('myMessage')
->atPath('property.path.name')
->setParameter('{{ value }}', 'Foo')
->setParameter('{{ value }}', '"Foo"')
->setInvalidValue('Foo')
->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
->assertRaised();
Expand All @@ -189,7 +197,7 @@ public function testValidateCustomErrorPath()

$this->buildViolation('myMessage')
->atPath('property.path.bar')
->setParameter('{{ value }}', 'Foo')
->setParameter('{{ value }}', '"Foo"')
->setInvalidValue('Foo')
->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
->assertRaised();
Expand Down Expand Up @@ -242,7 +250,7 @@ public function testValidateUniquenessWithIgnoreNull()

$this->buildViolation('myMessage')
->atPath('property.path.name')
->setParameter('{{ value }}', 'Foo')
->setParameter('{{ value }}', '"Foo"')
->setInvalidValue('Foo')
->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
->assertRaised();
Expand Down Expand Up @@ -275,7 +283,7 @@ public function testValidateUniquenessWithValidCustomErrorPath()

$this->buildViolation('myMessage')
->atPath('property.path.name2')
->setParameter('{{ value }}', 'Bar')
->setParameter('{{ value }}', '"Bar"')
->setInvalidValue('Bar')
->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
->assertRaised();
Expand Down Expand Up @@ -446,7 +454,7 @@ public function testValidateUniquenessNotToStringEntityWithAssociatedEntity()

$this->buildViolation('myMessage')
->atPath('property.path.single')
->setParameter('{{ value }}', $expectedValue)
->setParameter('{{ value }}', '"'.$expectedValue.'"')
->setInvalidValue($expectedValue)
->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
->assertRaised();
Expand All @@ -472,6 +480,44 @@ public function testAssociatedEntityWithNull()
$this->assertNoViolation();
}

public function testValidateUniquenessWithArrayValue()
{
$repository = $this->createRepositoryMock();
$this->repositoryFactory->setRepository($this->em, 'Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity', $repository);

$constraint = new UniqueEntity(array(
'message' => 'myMessage',
'fields' => array('phoneNumbers'),
'em' => self::EM_NAME,
'repositoryMethod' => 'findByCustom',
));

$entity1 = new SingleIntIdEntity(1, 'foo');
$entity1->phoneNumbers[] = 123;

$repository->expects($this->once())
->method('findByCustom')
->will($this->returnValue(array($entity1)))
;

$this->em->persist($entity1);
$this->em->flush();

$entity2 = new SingleIntIdEntity(2, 'bar');
$entity2->phoneNumbers[] = 123;
$this->em->persist($entity2);
$this->em->flush();

$this->validator->validate($entity2, $constraint);

$this->buildViolation('myMessage')
->atPath('property.path.phoneNumbers')
->setParameter('{{ value }}', 'array')
->setInvalidValue(array(123))
->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
->assertRaised();
}

/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
* @expectedExceptionMessage Object manager "foo" does not exist.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ public function validate($entity, Constraint $constraint)

$this->context->buildViolation($constraint->message)
->atPath($errorPath)
->setParameter('{{ value }}', $invalidValue)
->setParameter('{{ value }}', $this->formatValue($invalidValue, static::OBJECT_TO_STRING | static::PRETTY_DATE))
->setInvalidValue($invalidValue)
->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
->addViolation();
Expand Down