Actualización

This commit is contained in:
Xes
2025-04-10 12:24:57 +02:00
parent 8969cc929d
commit 45420b6f0d
39760 changed files with 4303286 additions and 0 deletions

View File

@@ -0,0 +1,66 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Doctrine\ContainerAwareEventManager;
use Symfony\Component\DependencyInjection\Container;
class ContainerAwareEventManagerTest extends TestCase
{
private $container;
private $evm;
protected function setUp()
{
$this->container = new Container();
$this->evm = new ContainerAwareEventManager($this->container);
}
public function testDispatchEvent()
{
$this->container->set('foobar', $listener1 = new MyListener());
$this->evm->addEventListener('foo', 'foobar');
$this->evm->addEventListener('foo', $listener2 = new MyListener());
$this->evm->dispatchEvent('foo');
$this->assertTrue($listener1->called);
$this->assertTrue($listener2->called);
}
public function testRemoveEventListener()
{
$this->evm->addEventListener('foo', 'bar');
$this->evm->addEventListener('foo', $listener = new MyListener());
$listeners = array('foo' => array('_service_bar' => 'bar', spl_object_hash($listener) => $listener));
$this->assertSame($listeners, $this->evm->getListeners());
$this->assertSame($listeners['foo'], $this->evm->getListeners('foo'));
$this->evm->removeEventListener('foo', $listener);
$this->assertSame(array('_service_bar' => 'bar'), $this->evm->getListeners('foo'));
$this->evm->removeEventListener('foo', 'bar');
$this->assertSame(array(), $this->evm->getListeners('foo'));
}
}
class MyListener
{
public $called = false;
public function foo()
{
$this->called = true;
}
}

View File

@@ -0,0 +1,172 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\DataCollector;
use Doctrine\DBAL\Platforms\MySqlPlatform;
use Doctrine\DBAL\Version;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Doctrine\DataCollector\DoctrineDataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class DoctrineDataCollectorTest extends TestCase
{
public function testCollectConnections()
{
$c = $this->createCollector(array());
$c->collect(new Request(), new Response());
$this->assertEquals(array('default' => 'doctrine.dbal.default_connection'), $c->getConnections());
}
public function testCollectManagers()
{
$c = $this->createCollector(array());
$c->collect(new Request(), new Response());
$this->assertEquals(array('default' => 'doctrine.orm.default_entity_manager'), $c->getManagers());
}
public function testCollectQueryCount()
{
$c = $this->createCollector(array());
$c->collect(new Request(), new Response());
$this->assertEquals(0, $c->getQueryCount());
$queries = array(
array('sql' => 'SELECT * FROM table1', 'params' => array(), 'types' => array(), 'executionMS' => 0),
);
$c = $this->createCollector($queries);
$c->collect(new Request(), new Response());
$this->assertEquals(1, $c->getQueryCount());
}
public function testCollectTime()
{
$c = $this->createCollector(array());
$c->collect(new Request(), new Response());
$this->assertEquals(0, $c->getTime());
$queries = array(
array('sql' => 'SELECT * FROM table1', 'params' => array(), 'types' => array(), 'executionMS' => 1),
);
$c = $this->createCollector($queries);
$c->collect(new Request(), new Response());
$this->assertEquals(1, $c->getTime());
$queries = array(
array('sql' => 'SELECT * FROM table1', 'params' => array(), 'types' => array(), 'executionMS' => 1),
array('sql' => 'SELECT * FROM table2', 'params' => array(), 'types' => array(), 'executionMS' => 2),
);
$c = $this->createCollector($queries);
$c->collect(new Request(), new Response());
$this->assertEquals(3, $c->getTime());
}
/**
* @dataProvider paramProvider
*/
public function testCollectQueries($param, $types, $expected, $explainable)
{
$queries = array(
array('sql' => 'SELECT * FROM table1 WHERE field1 = ?1', 'params' => array($param), 'types' => $types, 'executionMS' => 1),
);
$c = $this->createCollector($queries);
$c->collect(new Request(), new Response());
$collectedQueries = $c->getQueries();
$this->assertEquals($expected, $collectedQueries['default'][0]['params'][0]);
$this->assertEquals($explainable, $collectedQueries['default'][0]['explainable']);
}
public function testCollectQueryWithNoParams()
{
$queries = array(
array('sql' => 'SELECT * FROM table1', 'params' => array(), 'types' => array(), 'executionMS' => 1),
array('sql' => 'SELECT * FROM table1', 'params' => null, 'types' => null, 'executionMS' => 1),
);
$c = $this->createCollector($queries);
$c->collect(new Request(), new Response());
$collectedQueries = $c->getQueries();
$this->assertEquals(array(), $collectedQueries['default'][0]['params']);
$this->assertTrue($collectedQueries['default'][0]['explainable']);
$this->assertEquals(array(), $collectedQueries['default'][1]['params']);
$this->assertTrue($collectedQueries['default'][1]['explainable']);
}
/**
* @dataProvider paramProvider
*/
public function testSerialization($param, $types, $expected, $explainable)
{
$queries = array(
array('sql' => 'SELECT * FROM table1 WHERE field1 = ?1', 'params' => array($param), 'types' => $types, 'executionMS' => 1),
);
$c = $this->createCollector($queries);
$c->collect(new Request(), new Response());
$c = unserialize(serialize($c));
$collectedQueries = $c->getQueries();
$this->assertEquals($expected, $collectedQueries['default'][0]['params'][0]);
$this->assertEquals($explainable, $collectedQueries['default'][0]['explainable']);
}
public function paramProvider()
{
$tests = array(
array('some value', array(), 'some value', true),
array(1, array(), 1, true),
array(true, array(), true, true),
array(null, array(), null, true),
array(new \DateTime('2011-09-11'), array('date'), '2011-09-11', true),
array(fopen(__FILE__, 'r'), array(), 'Resource(stream)', false),
array(new \SplFileInfo(__FILE__), array(), 'Object(SplFileInfo)', false),
);
if (version_compare(Version::VERSION, '2.6', '>=')) {
$tests[] = array('this is not a date', array('date'), 'this is not a date', false);
$tests[] = array(new \stdClass(), array('date'), 'Object(stdClass)', false);
}
return $tests;
}
private function createCollector($queries)
{
$connection = $this->getMockBuilder('Doctrine\DBAL\Connection')
->disableOriginalConstructor()
->getMock();
$connection->expects($this->any())
->method('getDatabasePlatform')
->will($this->returnValue(new MySqlPlatform()));
$registry = $this->getMockBuilder('Doctrine\Common\Persistence\ManagerRegistry')->getMock();
$registry
->expects($this->any())
->method('getConnectionNames')
->will($this->returnValue(array('default' => 'doctrine.dbal.default_connection')));
$registry
->expects($this->any())
->method('getManagerNames')
->will($this->returnValue(array('default' => 'doctrine.orm.default_entity_manager')));
$registry->expects($this->any())
->method('getConnection')
->will($this->returnValue($connection));
$logger = $this->getMockBuilder('Doctrine\DBAL\Logging\DebugStack')->getMock();
$logger->queries = $queries;
$collector = new DoctrineDataCollector($registry);
$collector->addLogger('default', $logger);
return $collector;
}
}

View File

@@ -0,0 +1,30 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\DataFixtures;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader;
use Symfony\Bridge\Doctrine\Tests\Fixtures\ContainerAwareFixture;
class ContainerAwareLoaderTest extends TestCase
{
public function testShouldSetContainerOnContainerAwareFixture()
{
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$loader = new ContainerAwareLoader($container);
$fixture = new ContainerAwareFixture();
$loader->addFixture($fixture);
$this->assertSame($container, $fixture->container);
}
}

View File

@@ -0,0 +1,285 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\DependencyInjection\CompilerPass;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass\RegisterEventListenersAndSubscribersPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
class RegisterEventListenersAndSubscribersPassTest extends TestCase
{
/**
* @expectedException \InvalidArgumentException
*/
public function testExceptionOnAbstractTaggedSubscriber()
{
$container = $this->createBuilder();
$abstractDefinition = new Definition('stdClass');
$abstractDefinition->setAbstract(true);
$abstractDefinition->addTag('doctrine.event_subscriber');
$container->setDefinition('a', $abstractDefinition);
$this->process($container);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testExceptionOnAbstractTaggedListener()
{
$container = $this->createBuilder();
$abstractDefinition = new Definition('stdClass');
$abstractDefinition->setAbstract(true);
$abstractDefinition->addTag('doctrine.event_listener', array('event' => 'test'));
$container->setDefinition('a', $abstractDefinition);
$this->process($container);
}
public function testProcessEventListenersWithPriorities()
{
$container = $this->createBuilder();
$container
->register('a', 'stdClass')
->setPublic(false)
->addTag('doctrine.event_listener', array(
'event' => 'bar',
))
->addTag('doctrine.event_listener', array(
'event' => 'foo',
'priority' => -5,
))
->addTag('doctrine.event_listener', array(
'event' => 'foo_bar',
'priority' => 3,
'lazy' => true,
))
;
$container
->register('b', 'stdClass')
->addTag('doctrine.event_listener', array(
'event' => 'foo',
))
;
$container
->register('c', 'stdClass')
->addTag('doctrine.event_listener', array(
'event' => 'foo_bar',
'priority' => 4,
))
;
$this->process($container);
$methodCalls = $container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls();
$this->assertEquals(
array(
array('addEventListener', array(array('foo_bar'), new Reference('c'))),
array('addEventListener', array(array('foo_bar'), new Reference('a'))),
array('addEventListener', array(array('bar'), new Reference('a'))),
array('addEventListener', array(array('foo'), new Reference('b'))),
array('addEventListener', array(array('foo'), new Reference('a'))),
),
$methodCalls
);
// not lazy so must be reference
$this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $methodCalls[0][1][1]);
// lazy so id instead of reference and must mark service public
$this->assertSame('a', $methodCalls[1][1][1]);
$this->assertTrue($container->getDefinition('a')->isPublic());
}
public function testProcessEventListenersWithMultipleConnections()
{
$container = $this->createBuilder(true);
$container
->register('a', 'stdClass')
->addTag('doctrine.event_listener', array(
'event' => 'onFlush',
))
;
$container
->register('b', 'stdClass')
->addTag('doctrine.event_listener', array(
'event' => 'onFlush',
'connection' => 'default',
))
;
$container
->register('c', 'stdClass')
->addTag('doctrine.event_listener', array(
'event' => 'onFlush',
'connection' => 'second',
))
;
$this->process($container);
$this->assertEquals(
array(
array('addEventListener', array(array('onFlush'), new Reference('a'))),
array('addEventListener', array(array('onFlush'), new Reference('b'))),
),
$container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls()
);
$this->assertEquals(
array(
array('addEventListener', array(array('onFlush'), new Reference('a'))),
array('addEventListener', array(array('onFlush'), new Reference('c'))),
),
$container->getDefinition('doctrine.dbal.second_connection.event_manager')->getMethodCalls()
);
}
public function testProcessEventSubscribersWithMultipleConnections()
{
$container = $this->createBuilder(true);
$container
->register('a', 'stdClass')
->addTag('doctrine.event_subscriber', array(
'event' => 'onFlush',
))
;
$container
->register('b', 'stdClass')
->addTag('doctrine.event_subscriber', array(
'event' => 'onFlush',
'connection' => 'default',
))
;
$container
->register('c', 'stdClass')
->addTag('doctrine.event_subscriber', array(
'event' => 'onFlush',
'connection' => 'second',
))
;
$this->process($container);
$this->assertEquals(
array(
array('addEventSubscriber', array(new Reference('a'))),
array('addEventSubscriber', array(new Reference('b'))),
),
$container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls()
);
$this->assertEquals(
array(
array('addEventSubscriber', array(new Reference('a'))),
array('addEventSubscriber', array(new Reference('c'))),
),
$container->getDefinition('doctrine.dbal.second_connection.event_manager')->getMethodCalls()
);
}
public function testProcessEventSubscribersWithPriorities()
{
$container = $this->createBuilder();
$container
->register('a', 'stdClass')
->addTag('doctrine.event_subscriber')
;
$container
->register('b', 'stdClass')
->addTag('doctrine.event_subscriber', array(
'priority' => 5,
))
;
$container
->register('c', 'stdClass')
->addTag('doctrine.event_subscriber', array(
'priority' => 10,
))
;
$container
->register('d', 'stdClass')
->addTag('doctrine.event_subscriber', array(
'priority' => 10,
))
;
$container
->register('e', 'stdClass')
->addTag('doctrine.event_subscriber', array(
'priority' => 10,
))
;
$this->process($container);
$this->assertEquals(
array(
array('addEventSubscriber', array(new Reference('c'))),
array('addEventSubscriber', array(new Reference('d'))),
array('addEventSubscriber', array(new Reference('e'))),
array('addEventSubscriber', array(new Reference('b'))),
array('addEventSubscriber', array(new Reference('a'))),
),
$container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls()
);
}
public function testProcessNoTaggedServices()
{
$container = $this->createBuilder(true);
$this->process($container);
$this->assertEquals(array(), $container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls());
$this->assertEquals(array(), $container->getDefinition('doctrine.dbal.second_connection.event_manager')->getMethodCalls());
}
private function process(ContainerBuilder $container)
{
$pass = new RegisterEventListenersAndSubscribersPass('doctrine.connections', 'doctrine.dbal.%s_connection.event_manager', 'doctrine');
$pass->process($container);
}
private function createBuilder($multipleConnections = false)
{
$container = new ContainerBuilder();
$connections = array('default' => 'doctrine.dbal.default_connection');
$container->register('doctrine.dbal.default_connection.event_manager', 'stdClass');
$container->register('doctrine.dbal.default_connection', 'stdClass');
if ($multipleConnections) {
$container->register('doctrine.dbal.second_connection.event_manager', 'stdClass');
$container->register('doctrine.dbal.second_connection', 'stdClass');
$connections['second'] = 'doctrine.dbal.second_connection';
}
$container->setParameter('doctrine.connections', $connections);
return $container;
}
}

View File

@@ -0,0 +1,283 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\DependencyInjection;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
/**
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class DoctrineExtensionTest extends TestCase
{
/**
* @var \Symfony\Bridge\Doctrine\DependencyInjection\AbstractDoctrineExtension
*/
private $extension;
protected function setUp()
{
parent::setUp();
$this->extension = $this
->getMockBuilder('Symfony\Bridge\Doctrine\DependencyInjection\AbstractDoctrineExtension')
->setMethods(array(
'getMappingResourceConfigDirectory',
'getObjectManagerElementName',
'getMappingObjectDefaultName',
'getMappingResourceExtension',
'load',
))
->getMock()
;
$this->extension->expects($this->any())
->method('getObjectManagerElementName')
->will($this->returnCallback(function ($name) {
return 'doctrine.orm.'.$name;
}));
}
/**
* @expectedException \LogicException
*/
public function testFixManagersAutoMappingsWithTwoAutomappings()
{
$emConfigs = array(
'em1' => array(
'auto_mapping' => true,
),
'em2' => array(
'auto_mapping' => true,
),
);
$bundles = array(
'FristBundle' => 'My\FristBundle',
'SecondBundle' => 'My\SecondBundle',
);
$reflection = new \ReflectionClass(\get_class($this->extension));
$method = $reflection->getMethod('fixManagersAutoMappings');
$method->setAccessible(true);
$method->invoke($this->extension, $emConfigs, $bundles);
}
public function getAutomappingData()
{
return array(
array(
array( // no auto mapping on em1
'auto_mapping' => false,
),
array( // no auto mapping on em2
'auto_mapping' => false,
),
array(),
array(),
),
array(
array( // no auto mapping on em1
'auto_mapping' => false,
),
array( // auto mapping enabled on em2
'auto_mapping' => true,
),
array(),
array(
'mappings' => array(
'FristBundle' => array(
'mapping' => true,
'is_bundle' => true,
),
'SecondBundle' => array(
'mapping' => true,
'is_bundle' => true,
),
),
),
),
array(
array( // no auto mapping on em1, but it defines SecondBundle as own
'auto_mapping' => false,
'mappings' => array(
'SecondBundle' => array(
'mapping' => true,
'is_bundle' => true,
),
),
),
array( // auto mapping enabled on em2
'auto_mapping' => true,
),
array(
'mappings' => array(
'SecondBundle' => array(
'mapping' => true,
'is_bundle' => true,
),
),
),
array(
'mappings' => array(
'FristBundle' => array(
'mapping' => true,
'is_bundle' => true,
),
),
),
),
);
}
/**
* @dataProvider getAutomappingData
*/
public function testFixManagersAutoMappings(array $originalEm1, array $originalEm2, array $expectedEm1, array $expectedEm2)
{
$emConfigs = array(
'em1' => $originalEm1,
'em2' => $originalEm2,
);
$bundles = array(
'FristBundle' => 'My\FristBundle',
'SecondBundle' => 'My\SecondBundle',
);
$reflection = new \ReflectionClass(\get_class($this->extension));
$method = $reflection->getMethod('fixManagersAutoMappings');
$method->setAccessible(true);
$newEmConfigs = $method->invoke($this->extension, $emConfigs, $bundles);
$this->assertEquals($newEmConfigs['em1'], array_merge(array(
'auto_mapping' => false,
), $expectedEm1));
$this->assertEquals($newEmConfigs['em2'], array_merge(array(
'auto_mapping' => false,
), $expectedEm2));
}
public function providerBasicDrivers()
{
return array(
array('doctrine.orm.cache.apc.class', array('type' => 'apc')),
array('doctrine.orm.cache.array.class', array('type' => 'array')),
array('doctrine.orm.cache.xcache.class', array('type' => 'xcache')),
array('doctrine.orm.cache.wincache.class', array('type' => 'wincache')),
array('doctrine.orm.cache.zenddata.class', array('type' => 'zenddata')),
array('doctrine.orm.cache.redis.class', array('type' => 'redis'), array('setRedis')),
array('doctrine.orm.cache.memcache.class', array('type' => 'memcache'), array('setMemcache')),
array('doctrine.orm.cache.memcached.class', array('type' => 'memcached'), array('setMemcached')),
);
}
/**
* @param string $class
* @param array $config
*
* @dataProvider providerBasicDrivers
*/
public function testLoadBasicCacheDriver($class, array $config, array $expectedCalls = array())
{
$container = $this->createContainer();
$cacheName = 'metadata_cache';
$objectManager = array(
'name' => 'default',
'metadata_cache_driver' => $config,
);
$this->invokeLoadCacheDriver($objectManager, $container, $cacheName);
$this->assertTrue($container->hasDefinition('doctrine.orm.default_metadata_cache'));
$definition = $container->getDefinition('doctrine.orm.default_metadata_cache');
$defCalls = $definition->getMethodCalls();
$expectedCalls[] = 'setNamespace';
$actualCalls = array_map(function ($call) {
return $call[0];
}, $defCalls);
$this->assertFalse($definition->isPublic());
$this->assertEquals("%$class%", $definition->getClass());
foreach (array_unique($expectedCalls) as $call) {
$this->assertContains($call, $actualCalls);
}
}
public function testServiceCacheDriver()
{
$cacheName = 'metadata_cache';
$container = $this->createContainer();
$definition = new Definition('%doctrine.orm.cache.apc.class%');
$objectManager = array(
'name' => 'default',
'metadata_cache_driver' => array(
'type' => 'service',
'id' => 'service_driver',
),
);
$container->setDefinition('service_driver', $definition);
$this->invokeLoadCacheDriver($objectManager, $container, $cacheName);
$this->assertTrue($container->hasAlias('doctrine.orm.default_metadata_cache'));
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage "unrecognized_type" is an unrecognized Doctrine cache driver.
*/
public function testUnrecognizedCacheDriverException()
{
$cacheName = 'metadata_cache';
$container = $this->createContainer();
$objectManager = array(
'name' => 'default',
'metadata_cache_driver' => array(
'type' => 'unrecognized_type',
),
);
$this->invokeLoadCacheDriver($objectManager, $container, $cacheName);
}
protected function invokeLoadCacheDriver(array $objectManager, ContainerBuilder $container, $cacheName)
{
$method = new \ReflectionMethod($this->extension, 'loadObjectManagerCacheDriver');
$method->setAccessible(true);
$method->invokeArgs($this->extension, array($objectManager, $container, $cacheName));
}
/**
* @return \Symfony\Component\DependencyInjection\ContainerBuilder
*/
protected function createContainer(array $data = array())
{
return new ContainerBuilder(new ParameterBag(array_merge(array(
'kernel.bundles' => array('FrameworkBundle' => 'Symfony\\Bundle\\FrameworkBundle\\FrameworkBundle'),
'kernel.cache_dir' => __DIR__,
'kernel.debug' => false,
'kernel.environment' => 'test',
'kernel.name' => 'kernel',
'kernel.root_dir' => __DIR__,
), $data)));
}
}

View File

@@ -0,0 +1,35 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests;
@trigger_error('The '.__NAMESPACE__.'\DoctrineOrmTestCase class is deprecated since Symfony 2.4 and will be removed in 3.0. Use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper class instead.', E_USER_DEPRECATED);
use Doctrine\ORM\EntityManager;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper;
/**
* Class DoctrineOrmTestCase.
*
* @deprecated since version 2.4, to be removed in 3.0.
* Use {@link DoctrineTestHelper} instead.
*/
abstract class DoctrineOrmTestCase extends TestCase
{
/**
* @return EntityManager
*/
public static function createTestEntityManager()
{
return DoctrineTestHelper::createTestEntityManager();
}
}

View File

@@ -0,0 +1,61 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\ExpressionLanguage;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Doctrine\ExpressionLanguage\DoctrineParserCache;
class DoctrineParserCacheTest extends TestCase
{
public function testFetch()
{
$doctrineCacheMock = $this->getMockBuilder('Doctrine\Common\Cache\Cache')->getMock();
$parserCache = new DoctrineParserCache($doctrineCacheMock);
$doctrineCacheMock->expects($this->once())
->method('fetch')
->will($this->returnValue('bar'));
$result = $parserCache->fetch('foo');
$this->assertEquals('bar', $result);
}
public function testFetchUnexisting()
{
$doctrineCacheMock = $this->getMockBuilder('Doctrine\Common\Cache\Cache')->getMock();
$parserCache = new DoctrineParserCache($doctrineCacheMock);
$doctrineCacheMock
->expects($this->once())
->method('fetch')
->will($this->returnValue(false));
$this->assertNull($parserCache->fetch(''));
}
public function testSave()
{
$doctrineCacheMock = $this->getMockBuilder('Doctrine\Common\Cache\Cache')->getMock();
$parserCache = new DoctrineParserCache($doctrineCacheMock);
$expression = $this->getMockBuilder('Symfony\Component\ExpressionLanguage\ParsedExpression')
->disableOriginalConstructor()
->getMock();
$doctrineCacheMock->expects($this->once())
->method('save')
->with('foo', $expression);
$parserCache->save('foo', $expression);
}
}

View File

@@ -0,0 +1,45 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Fixtures;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class AssociationEntity
{
/**
* @var int
* @ORM\Id @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="SingleIntIdEntity")
*
* @var \Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity
*/
public $single;
/**
* @ORM\ManyToOne(targetEntity="CompositeIntIdEntity")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="composite_id1", referencedColumnName="id1"),
* @ORM\JoinColumn(name="composite_id2", referencedColumnName="id2")
* })
*
* @var \Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity
*/
public $composite;
}

View File

@@ -0,0 +1,41 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Fixtures;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Id;
/** @Entity */
class CompositeIntIdEntity
{
/** @Id @Column(type="integer") */
protected $id1;
/** @Id @Column(type="integer") */
protected $id2;
/** @Column(type="string") */
public $name;
public function __construct($id1, $id2, $name)
{
$this->id1 = $id1;
$this->id2 = $id2;
$this->name = $name;
}
public function __toString()
{
return $this->name;
}
}

View File

@@ -0,0 +1,41 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Fixtures;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Id;
/** @Entity */
class CompositeStringIdEntity
{
/** @Id @Column(type="string") */
protected $id1;
/** @Id @Column(type="string") */
protected $id2;
/** @Column(type="string") */
public $name;
public function __construct($id1, $id2, $name)
{
$this->id1 = $id1;
$this->id2 = $id2;
$this->name = $name;
}
public function __toString()
{
return $this->name;
}
}

View File

@@ -0,0 +1,31 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Fixtures;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ContainerAwareFixture implements FixtureInterface, ContainerAwareInterface
{
public $container;
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
public function load(ObjectManager $manager)
{
}
}

View File

@@ -0,0 +1,36 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Fixtures;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Id;
/** @Entity */
class DoubleNameEntity
{
/** @Id @Column(type="integer") */
protected $id;
/** @Column(type="string") */
public $name;
/** @Column(type="string", nullable=true) */
public $name2;
public function __construct($id, $name, $name2)
{
$this->id = $id;
$this->name = $name;
$this->name2 = $name2;
}
}

View File

@@ -0,0 +1,36 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Fixtures;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Id;
/** @Entity */
class DoubleNullableNameEntity
{
/** @Id @Column(type="integer") */
protected $id;
/** @Column(type="string", nullable=true) */
public $name;
/** @Column(type="string", nullable=true) */
public $name2;
public function __construct($id, $name, $name2)
{
$this->id = $id;
$this->name = $name;
$this->name2 = $name2;
}
}

View File

@@ -0,0 +1,28 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Fixtures\Embeddable;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Embeddable
*/
class Identifier
{
/**
* @var int
*
* @ORM\Id
* @ORM\Column(type="integer")
*/
protected $value;
}

View File

@@ -0,0 +1,27 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Fixtures;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class EmbeddedIdentifierEntity
{
/**
* @var Embeddable\Identifier
*
* @ORM\Embedded(class="Symfony\Bridge\Doctrine\Tests\Fixtures\Embeddable\Identifier")
*/
protected $id;
}

View File

@@ -0,0 +1,36 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Fixtures;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Id;
/** @Entity */
class GroupableEntity
{
/** @Id @Column(type="integer") */
protected $id;
/** @Column(type="string", nullable=true) */
public $name;
/** @Column(type="string", nullable=true) */
public $groupName;
public function __construct($id, $name, $groupName)
{
$this->id = $id;
$this->name = $name;
$this->groupName = $groupName;
}
}

View File

@@ -0,0 +1,28 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Fixtures;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Id;
/** @Entity */
class GuidIdEntity
{
/** @Id @Column(type="guid") */
protected $id;
public function __construct($id)
{
$this->id = $id;
}
}

View File

@@ -0,0 +1,38 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Fixtures;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\OneToOne;
/** @Entity */
class SingleAssociationToIntIdEntity
{
/** @Id @OneToOne(targetEntity="SingleIntIdNoToStringEntity", cascade={"ALL"}) */
protected $entity;
/** @Column(type="string", nullable=true) */
public $name;
public function __construct(SingleIntIdNoToStringEntity $entity, $name)
{
$this->entity = $entity;
$this->name = $name;
}
public function __toString()
{
return (string) $this->name;
}
}

View File

@@ -0,0 +1,37 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Fixtures;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Id;
/** @Entity */
class SingleIntIdEntity
{
/** @Id @Column(type="integer") */
protected $id;
/** @Column(type="string", nullable=true) */
public $name;
public function __construct($id, $name)
{
$this->id = $id;
$this->name = $name;
}
public function __toString()
{
return (string) $this->name;
}
}

View File

@@ -0,0 +1,32 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Fixtures;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Id;
/** @Entity */
class SingleIntIdNoToStringEntity
{
/** @Id @Column(type="integer") */
protected $id;
/** @Column(type="string", nullable=true) */
public $name;
public function __construct($id, $name)
{
$this->id = $id;
$this->name = $name;
}
}

View File

@@ -0,0 +1,57 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Fixtures;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Id;
/** @Entity */
class SingleStringCastableIdEntity
{
/**
* @Id
* @Column(type="string")
* @GeneratedValue(strategy="NONE")
*/
protected $id;
/** @Column(type="string", nullable=true) */
public $name;
public function __construct($id, $name)
{
$this->id = new StringCastableObjectIdentity($id);
$this->name = $name;
}
public function __toString()
{
return (string) $this->name;
}
}
class StringCastableObjectIdentity
{
protected $id;
public function __construct($id)
{
$this->id = $id;
}
public function __toString()
{
return (string) $this->id;
}
}

View File

@@ -0,0 +1,37 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Fixtures;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Id;
/** @Entity */
class SingleStringIdEntity
{
/** @Id @Column(type="string") */
protected $id;
/** @Column(type="string") */
public $name;
public function __construct($id, $name)
{
$this->id = $id;
$this->name = $name;
}
public function __toString()
{
return $this->name;
}
}

View File

@@ -0,0 +1,62 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Fixtures;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Id;
use Symfony\Component\Security\Core\User\UserInterface;
/** @Entity */
class User implements UserInterface
{
/** @Id @Column(type="integer") */
protected $id1;
/** @Id @Column(type="integer") */
protected $id2;
/** @Column(type="string") */
public $name;
public function __construct($id1, $id2, $name)
{
$this->id1 = $id1;
$this->id2 = $id2;
$this->name = $name;
}
public function getRoles()
{
}
public function getPassword()
{
}
public function getSalt()
{
}
public function getUsername()
{
return $this->name;
}
public function eraseCredentials()
{
}
public function equals(UserInterface $user)
{
}
}

View File

@@ -0,0 +1,28 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Fixtures;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Id;
/** @Entity */
class UuidIdEntity
{
/** @Id @Column(type="uuid") */
protected $id;
public function __construct($id)
{
$this->id = $id;
}
}

View File

@@ -0,0 +1,62 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;
use Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity;
if (!class_exists('Symfony\Component\Form\Tests\Extension\Core\ChoiceList\AbstractChoiceListTest')) {
return;
}
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
abstract class AbstractEntityChoiceListCompositeIdTest extends AbstractEntityChoiceListTest
{
protected function getEntityClass()
{
return 'Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity';
}
/**
* @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
*/
protected function createObjects()
{
return array(
new CompositeIntIdEntity(10, 11, 'A'),
new CompositeIntIdEntity(20, 21, 'B'),
new CompositeIntIdEntity(30, 31, 'C'),
new CompositeIntIdEntity(40, 41, 'D'),
);
}
protected function getChoices()
{
return array(0 => $this->obj1, 1 => $this->obj2, 2 => $this->obj3, 3 => $this->obj4);
}
protected function getLabels()
{
return array(0 => 'A', 1 => 'B', 2 => 'C', 3 => 'D');
}
protected function getValues()
{
return array(0 => '0', 1 => '1', 2 => '2', 3 => '3');
}
protected function getIndices()
{
return array(0, 1, 2, 3);
}
}

View File

@@ -0,0 +1,91 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;
use Symfony\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList;
use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleAssociationToIntIdEntity;
use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdNoToStringEntity;
if (!class_exists('Symfony\Component\Form\Tests\Extension\Core\ChoiceList\AbstractChoiceListTest')) {
return;
}
/**
* Test choices generated from an entity with a primary foreign key.
*
* @author Premi Giorgio <giosh94mhz@gmail.com>
* @author Bernhard Schussek <bschussek@gmail.com>
* @group legacy
*/
abstract class AbstractEntityChoiceListSingleAssociationToIntIdTest extends AbstractEntityChoiceListTest
{
protected function getEntityClass()
{
return 'Symfony\Bridge\Doctrine\Tests\Fixtures\SingleAssociationToIntIdEntity';
}
protected function getClassesMetadata()
{
return array(
$this->em->getClassMetadata($this->getEntityClass()),
$this->em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdNoToStringEntity'),
);
}
protected function createChoiceList()
{
return new EntityChoiceList($this->em, $this->getEntityClass(), 'name');
}
/**
* @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
*/
protected function createObjects()
{
$innerA = new SingleIntIdNoToStringEntity(-10, 'inner_A');
$innerB = new SingleIntIdNoToStringEntity(10, 'inner_B');
$innerC = new SingleIntIdNoToStringEntity(20, 'inner_C');
$innerD = new SingleIntIdNoToStringEntity(30, 'inner_D');
$this->em->persist($innerA);
$this->em->persist($innerB);
$this->em->persist($innerC);
$this->em->persist($innerD);
return array(
new SingleAssociationToIntIdEntity($innerA, 'A'),
new SingleAssociationToIntIdEntity($innerB, 'B'),
new SingleAssociationToIntIdEntity($innerC, 'C'),
new SingleAssociationToIntIdEntity($innerD, 'D'),
);
}
protected function getChoices()
{
return array('_10' => $this->obj1, 10 => $this->obj2, 20 => $this->obj3, 30 => $this->obj4);
}
protected function getLabels()
{
return array('_10' => 'A', 10 => 'B', 20 => 'C', 30 => 'D');
}
protected function getValues()
{
return array('_10' => '-10', 10 => '10', 20 => '20', 30 => '30');
}
protected function getIndices()
{
return array('_10', 10, 20, 30);
}
}

View File

@@ -0,0 +1,62 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;
use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity;
if (!class_exists('Symfony\Component\Form\Tests\Extension\Core\ChoiceList\AbstractChoiceListTest')) {
return;
}
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
abstract class AbstractEntityChoiceListSingleIntIdTest extends AbstractEntityChoiceListTest
{
protected function getEntityClass()
{
return 'Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity';
}
/**
* @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
*/
protected function createObjects()
{
return array(
new SingleIntIdEntity(-10, 'A'),
new SingleIntIdEntity(10, 'B'),
new SingleIntIdEntity(20, 'C'),
new SingleIntIdEntity(30, 'D'),
);
}
protected function getChoices()
{
return array('_10' => $this->obj1, 10 => $this->obj2, 20 => $this->obj3, 30 => $this->obj4);
}
protected function getLabels()
{
return array('_10' => 'A', 10 => 'B', 20 => 'C', 30 => 'D');
}
protected function getValues()
{
return array('_10' => '-10', 10 => '10', 20 => '20', 30 => '30');
}
protected function getIndices()
{
return array('_10', 10, 20, 30);
}
}

View File

@@ -0,0 +1,62 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;
use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleStringIdEntity;
if (!class_exists('Symfony\Component\Form\Tests\Extension\Core\ChoiceList\AbstractChoiceListTest')) {
return;
}
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
abstract class AbstractEntityChoiceListSingleStringIdTest extends AbstractEntityChoiceListTest
{
protected function getEntityClass()
{
return 'Symfony\Bridge\Doctrine\Tests\Fixtures\SingleStringIdEntity';
}
/**
* @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
*/
protected function createObjects()
{
return array(
new SingleStringIdEntity('a', 'A'),
new SingleStringIdEntity('b', 'B'),
new SingleStringIdEntity('c', 'C'),
new SingleStringIdEntity('d', 'D'),
);
}
protected function getChoices()
{
return array(0 => $this->obj1, 1 => $this->obj2, 2 => $this->obj3, 3 => $this->obj4);
}
protected function getLabels()
{
return array(0 => 'A', 1 => 'B', 2 => 'C', 3 => 'D');
}
protected function getValues()
{
return array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd');
}
protected function getIndices()
{
return array(0, 1, 2, 3);
}
}

View File

@@ -0,0 +1,92 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;
use Doctrine\ORM\Tools\SchemaTool;
use Symfony\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList;
use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper;
use Symfony\Component\Form\Tests\Extension\Core\ChoiceList\AbstractChoiceListTest;
if (!class_exists('Symfony\Component\Form\Tests\Extension\Core\ChoiceList\AbstractChoiceListTest')) {
return;
}
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
abstract class AbstractEntityChoiceListTest extends AbstractChoiceListTest
{
/**
* @var \Doctrine\ORM\EntityManager
*/
protected $em;
protected $obj1;
protected $obj2;
protected $obj3;
protected $obj4;
protected function setUp()
{
$this->em = DoctrineTestHelper::createTestEntityManager();
$schemaTool = new SchemaTool($this->em);
$classes = $this->getClassesMetadata();
try {
$schemaTool->dropSchema($classes);
} catch (\Exception $e) {
}
try {
$schemaTool->createSchema($classes);
} catch (\Exception $e) {
}
list($this->obj1, $this->obj2, $this->obj3, $this->obj4) = $this->createObjects();
$this->em->persist($this->obj1);
$this->em->persist($this->obj2);
$this->em->persist($this->obj3);
$this->em->persist($this->obj4);
$this->em->flush();
parent::setUp();
}
protected function tearDown()
{
parent::tearDown();
$this->em = null;
}
abstract protected function getEntityClass();
abstract protected function createObjects();
protected function getClassesMetadata()
{
return array($this->em->getClassMetadata($this->getEntityClass()));
}
/**
* @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
*/
protected function createChoiceList()
{
return new EntityChoiceList($this->em, $this->getEntityClass());
}
}

View File

@@ -0,0 +1,460 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\Persistence\ObjectRepository;
use Doctrine\ORM\Mapping\ClassMetadata;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Doctrine\Form\ChoiceList\DoctrineChoiceLoader;
use Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface;
use Symfony\Bridge\Doctrine\Form\ChoiceList\IdReader;
use Symfony\Component\Form\ChoiceList\ArrayChoiceList;
use Symfony\Component\Form\ChoiceList\Factory\ChoiceListFactoryInterface;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class DoctrineChoiceLoaderTest extends TestCase
{
/**
* @var ChoiceListFactoryInterface|\PHPUnit_Framework_MockObject_MockObject
*/
private $factory;
/**
* @var ObjectManager|\PHPUnit_Framework_MockObject_MockObject
*/
private $om;
/**
* @var ObjectRepository|\PHPUnit_Framework_MockObject_MockObject
*/
private $repository;
/**
* @var string
*/
private $class;
/**
* @var IdReader|\PHPUnit_Framework_MockObject_MockObject
*/
private $idReader;
/**
* @var EntityLoaderInterface|\PHPUnit_Framework_MockObject_MockObject
*/
private $objectLoader;
/**
* @var \stdClass
*/
private $obj1;
/**
* @var \stdClass
*/
private $obj2;
/**
* @var \stdClass
*/
private $obj3;
protected function setUp()
{
$this->factory = $this->getMockBuilder('Symfony\Component\Form\ChoiceList\Factory\ChoiceListFactoryInterface')->getMock();
$this->om = $this->getMockBuilder('Doctrine\Common\Persistence\ObjectManager')->getMock();
$this->repository = $this->getMockBuilder('Doctrine\Common\Persistence\ObjectRepository')->getMock();
$this->class = 'stdClass';
$this->idReader = $this->getMockBuilder('Symfony\Bridge\Doctrine\Form\ChoiceList\IdReader')
->disableOriginalConstructor()
->getMock();
$this->objectLoader = $this->getMockBuilder('Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface')->getMock();
$this->obj1 = (object) array('name' => 'A');
$this->obj2 = (object) array('name' => 'B');
$this->obj3 = (object) array('name' => 'C');
$this->om->expects($this->any())
->method('getRepository')
->with($this->class)
->willReturn($this->repository);
$this->om->expects($this->any())
->method('getClassMetadata')
->with($this->class)
->willReturn(new ClassMetadata($this->class));
}
public function testLoadChoiceList()
{
$loader = new DoctrineChoiceLoader(
$this->factory,
$this->om,
$this->class,
$this->idReader
);
$choices = array($this->obj1, $this->obj2, $this->obj3);
$choiceList = new ArrayChoiceList(array());
$value = function () {};
$this->repository->expects($this->once())
->method('findAll')
->willReturn($choices);
$this->factory->expects($this->once())
->method('createListFromChoices')
->with($choices, $value)
->willReturn($choiceList);
$this->assertSame($choiceList, $loader->loadChoiceList($value));
// no further loads on subsequent calls
$this->assertSame($choiceList, $loader->loadChoiceList($value));
}
public function testLoadChoiceListUsesObjectLoaderIfAvailable()
{
$loader = new DoctrineChoiceLoader(
$this->factory,
$this->om,
$this->class,
$this->idReader,
$this->objectLoader
);
$choices = array($this->obj1, $this->obj2, $this->obj3);
$choiceList = new ArrayChoiceList(array());
$this->repository->expects($this->never())
->method('findAll');
$this->objectLoader->expects($this->once())
->method('getEntities')
->willReturn($choices);
$this->factory->expects($this->once())
->method('createListFromChoices')
->with($choices)
->willReturn($choiceList);
$this->assertSame($choiceList, $loader->loadChoiceList());
// no further loads on subsequent calls
$this->assertSame($choiceList, $loader->loadChoiceList());
}
public function testLoadValuesForChoices()
{
$loader = new DoctrineChoiceLoader(
$this->factory,
$this->om,
$this->class,
$this->idReader
);
$choices = array($this->obj1, $this->obj2, $this->obj3);
$choiceList = new ArrayChoiceList($choices);
$this->repository->expects($this->once())
->method('findAll')
->willReturn($choices);
$this->factory->expects($this->once())
->method('createListFromChoices')
->with($choices)
->willReturn($choiceList);
$this->assertSame(array('1', '2'), $loader->loadValuesForChoices(array($this->obj2, $this->obj3)));
// no further loads on subsequent calls
$this->assertSame(array('1', '2'), $loader->loadValuesForChoices(array($this->obj2, $this->obj3)));
}
public function testLoadValuesForChoicesDoesNotLoadIfEmptyChoices()
{
$loader = new DoctrineChoiceLoader(
$this->factory,
$this->om,
$this->class,
$this->idReader
);
$this->repository->expects($this->never())
->method('findAll');
$this->factory->expects($this->never())
->method('createListFromChoices');
$this->assertSame(array(), $loader->loadValuesForChoices(array()));
}
public function testLoadValuesForChoicesDoesNotLoadIfSingleIntId()
{
$loader = new DoctrineChoiceLoader(
$this->factory,
$this->om,
$this->class,
$this->idReader
);
$this->idReader->expects($this->any())
->method('isSingleId')
->willReturn(true);
$this->repository->expects($this->never())
->method('findAll');
$this->factory->expects($this->never())
->method('createListFromChoices');
$this->idReader->expects($this->any())
->method('getIdValue')
->with($this->obj2)
->willReturn('2');
$this->assertSame(array('2'), $loader->loadValuesForChoices(array($this->obj2)));
}
public function testLoadValuesForChoicesLoadsIfSingleIntIdAndValueGiven()
{
$loader = new DoctrineChoiceLoader(
$this->factory,
$this->om,
$this->class,
$this->idReader
);
$choices = array($this->obj1, $this->obj2, $this->obj3);
$value = function (\stdClass $object) { return $object->name; };
$choiceList = new ArrayChoiceList($choices, $value);
$this->idReader->expects($this->any())
->method('isSingleId')
->willReturn(true);
$this->repository->expects($this->once())
->method('findAll')
->willReturn($choices);
$this->factory->expects($this->once())
->method('createListFromChoices')
->with($choices, $value)
->willReturn($choiceList);
$this->assertSame(array('B'), $loader->loadValuesForChoices(
array($this->obj2),
$value
));
}
public function testLoadValuesForChoicesDoesNotLoadIfValueIsIdReader()
{
$loader = new DoctrineChoiceLoader(
$this->factory,
$this->om,
$this->class,
$this->idReader
);
$value = array($this->idReader, 'getIdValue');
$this->idReader->expects($this->any())
->method('isSingleId')
->willReturn(true);
$this->repository->expects($this->never())
->method('findAll');
$this->factory->expects($this->never())
->method('createListFromChoices');
$this->idReader->expects($this->any())
->method('getIdValue')
->with($this->obj2)
->willReturn('2');
$this->assertSame(array('2'), $loader->loadValuesForChoices(
array($this->obj2),
$value
));
}
public function testLoadChoicesForValues()
{
$loader = new DoctrineChoiceLoader(
$this->factory,
$this->om,
$this->class,
$this->idReader
);
$choices = array($this->obj1, $this->obj2, $this->obj3);
$choiceList = new ArrayChoiceList($choices);
$this->repository->expects($this->once())
->method('findAll')
->willReturn($choices);
$this->factory->expects($this->once())
->method('createListFromChoices')
->with($choices)
->willReturn($choiceList);
$this->assertSame(array($this->obj2, $this->obj3), $loader->loadChoicesForValues(array('1', '2')));
// no further loads on subsequent calls
$this->assertSame(array($this->obj2, $this->obj3), $loader->loadChoicesForValues(array('1', '2')));
}
public function testLoadChoicesForValuesDoesNotLoadIfEmptyValues()
{
$loader = new DoctrineChoiceLoader(
$this->factory,
$this->om,
$this->class,
$this->idReader
);
$this->repository->expects($this->never())
->method('findAll');
$this->factory->expects($this->never())
->method('createListFromChoices');
$this->assertSame(array(), $loader->loadChoicesForValues(array()));
}
public function testLoadChoicesForValuesLoadsOnlyChoicesIfSingleIntId()
{
$loader = new DoctrineChoiceLoader(
$this->factory,
$this->om,
$this->class,
$this->idReader,
$this->objectLoader
);
$choices = array($this->obj2, $this->obj3);
$this->idReader->expects($this->any())
->method('isSingleId')
->willReturn(true);
$this->idReader->expects($this->any())
->method('getIdField')
->willReturn('idField');
$this->repository->expects($this->never())
->method('findAll');
$this->factory->expects($this->never())
->method('createListFromChoices');
$this->objectLoader->expects($this->once())
->method('getEntitiesByIds')
->with('idField', array(4 => '3', 7 => '2'))
->willReturn($choices);
$this->idReader->expects($this->any())
->method('getIdValue')
->willReturnMap(array(
array($this->obj2, '2'),
array($this->obj3, '3'),
));
$this->assertSame(
array(4 => $this->obj3, 7 => $this->obj2),
$loader->loadChoicesForValues(array(4 => '3', 7 => '2')
));
}
public function testLoadChoicesForValuesLoadsAllIfSingleIntIdAndValueGiven()
{
$loader = new DoctrineChoiceLoader(
$this->factory,
$this->om,
$this->class,
$this->idReader
);
$choices = array($this->obj1, $this->obj2, $this->obj3);
$value = function (\stdClass $object) { return $object->name; };
$choiceList = new ArrayChoiceList($choices, $value);
$this->idReader->expects($this->any())
->method('isSingleId')
->willReturn(true);
$this->repository->expects($this->once())
->method('findAll')
->willReturn($choices);
$this->factory->expects($this->once())
->method('createListFromChoices')
->with($choices, $value)
->willReturn($choiceList);
$this->assertSame(array($this->obj2), $loader->loadChoicesForValues(
array('B'),
$value
));
}
public function testLoadChoicesForValuesLoadsOnlyChoicesIfValueIsIdReader()
{
$loader = new DoctrineChoiceLoader(
$this->factory,
$this->om,
$this->class,
$this->idReader,
$this->objectLoader
);
$choices = array($this->obj2, $this->obj3);
$value = array($this->idReader, 'getIdValue');
$this->idReader->expects($this->any())
->method('isSingleId')
->willReturn(true);
$this->idReader->expects($this->any())
->method('getIdField')
->willReturn('idField');
$this->repository->expects($this->never())
->method('findAll');
$this->factory->expects($this->never())
->method('createListFromChoices');
$this->objectLoader->expects($this->once())
->method('getEntitiesByIds')
->with('idField', array('2'))
->willReturn($choices);
$this->idReader->expects($this->any())
->method('getIdValue')
->willReturnMap(array(
array($this->obj2, '2'),
array($this->obj3, '3'),
));
$this->assertSame(array($this->obj2), $loader->loadChoicesForValues(array('2'), $value));
}
}

View File

@@ -0,0 +1,289 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;
use Doctrine\ORM\Tools\SchemaTool;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList;
use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper;
use Symfony\Bridge\Doctrine\Tests\Fixtures\GroupableEntity;
use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity;
use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdNoToStringEntity;
use Symfony\Component\Form\Extension\Core\View\ChoiceView;
/**
* @group legacy
*/
class GenericEntityChoiceListTest extends TestCase
{
const SINGLE_INT_ID_CLASS = 'Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity';
const SINGLE_STRING_ID_CLASS = 'Symfony\Bridge\Doctrine\Tests\Fixtures\SingleStringIdEntity';
const COMPOSITE_ID_CLASS = 'Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity';
const GROUPABLE_CLASS = 'Symfony\Bridge\Doctrine\Tests\Fixtures\GroupableEntity';
/**
* @var \Doctrine\ORM\EntityManager
*/
private $em;
protected function setUp()
{
$this->em = DoctrineTestHelper::createTestEntityManager();
$schemaTool = new SchemaTool($this->em);
$classes = array(
$this->em->getClassMetadata(self::SINGLE_INT_ID_CLASS),
$this->em->getClassMetadata(self::SINGLE_STRING_ID_CLASS),
$this->em->getClassMetadata(self::COMPOSITE_ID_CLASS),
$this->em->getClassMetadata(self::GROUPABLE_CLASS),
);
try {
$schemaTool->dropSchema($classes);
} catch (\Exception $e) {
}
try {
$schemaTool->createSchema($classes);
} catch (\Exception $e) {
}
parent::setUp();
}
protected function tearDown()
{
parent::tearDown();
$this->em = null;
}
/**
* @expectedException \Symfony\Component\Form\Exception\StringCastException
* @expectedMessage Entity "Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity" passed to the choice field must have a "__toString()" method defined (or you can also override the "property" option).
*/
public function testEntitiesMustHaveAToStringMethod()
{
$entity1 = new SingleIntIdNoToStringEntity(1, 'Foo');
$entity2 = new SingleIntIdNoToStringEntity(2, 'Bar');
// Persist for managed state
$this->em->persist($entity1);
$this->em->persist($entity2);
$choiceList = new EntityChoiceList(
$this->em,
self::SINGLE_INT_ID_CLASS,
null,
null,
array(
$entity1,
$entity2,
)
);
$choiceList->getValues();
}
/**
* @expectedException \Symfony\Component\Form\Exception\RuntimeException
*/
public function testChoicesMustBeManaged()
{
$entity1 = new SingleIntIdEntity(1, 'Foo');
$entity2 = new SingleIntIdEntity(2, 'Bar');
// no persist here!
$choiceList = new EntityChoiceList(
$this->em,
self::SINGLE_INT_ID_CLASS,
'name',
null,
array(
$entity1,
$entity2,
)
);
// triggers loading -> exception
$choiceList->getChoices();
}
public function testInitExplicitChoices()
{
$entity1 = new SingleIntIdEntity(1, 'Foo');
$entity2 = new SingleIntIdEntity(2, 'Bar');
// Persist for managed state
$this->em->persist($entity1);
$this->em->persist($entity2);
$choiceList = new EntityChoiceList(
$this->em,
self::SINGLE_INT_ID_CLASS,
'name',
null,
array(
$entity1,
$entity2,
)
);
$this->assertSame(array(1 => $entity1, 2 => $entity2), $choiceList->getChoices());
}
public function testInitEmptyChoices()
{
$entity1 = new SingleIntIdEntity(1, 'Foo');
$entity2 = new SingleIntIdEntity(2, 'Bar');
// Persist for managed state
$this->em->persist($entity1);
$this->em->persist($entity2);
$choiceList = new EntityChoiceList(
$this->em,
self::SINGLE_INT_ID_CLASS,
'name',
null,
array()
);
$this->assertSame(array(), $choiceList->getChoices());
}
public function testInitNestedChoices()
{
$entity1 = new SingleIntIdEntity(1, 'Foo');
$entity2 = new SingleIntIdEntity(2, 'Bar');
// Oh yeah, we're persisting with fire now!
$this->em->persist($entity1);
$this->em->persist($entity2);
$choiceList = new EntityChoiceList(
$this->em,
self::SINGLE_INT_ID_CLASS,
'name',
null,
array(
'group1' => array($entity1),
'group2' => array($entity2),
),
array()
);
$this->assertSame(array(1 => $entity1, 2 => $entity2), $choiceList->getChoices());
$this->assertEquals(array(
'group1' => array(1 => new ChoiceView($entity1, '1', 'Foo')),
'group2' => array(2 => new ChoiceView($entity2, '2', 'Bar')),
), $choiceList->getRemainingViews());
}
public function testGroupByPropertyPath()
{
$item1 = new GroupableEntity(1, 'Foo', 'Group1');
$item2 = new GroupableEntity(2, 'Bar', 'Group1');
$item3 = new GroupableEntity(3, 'Baz', 'Group2');
$item4 = new GroupableEntity(4, 'Boo!', null);
$this->em->persist($item1);
$this->em->persist($item2);
$this->em->persist($item3);
$this->em->persist($item4);
$choiceList = new EntityChoiceList(
$this->em,
self::GROUPABLE_CLASS,
'name',
null,
array(
$item1,
$item2,
$item3,
$item4,
),
array(),
'groupName'
);
$this->assertEquals(array(1 => $item1, 2 => $item2, 3 => $item3, 4 => $item4), $choiceList->getChoices());
$this->assertEquals(array(
'Group1' => array(1 => new ChoiceView($item1, '1', 'Foo'), 2 => new ChoiceView($item2, '2', 'Bar')),
'Group2' => array(3 => new ChoiceView($item3, '3', 'Baz')),
4 => new ChoiceView($item4, '4', 'Boo!'),
), $choiceList->getRemainingViews());
}
public function testGroupByInvalidPropertyPathReturnsFlatChoices()
{
$item1 = new GroupableEntity(1, 'Foo', 'Group1');
$item2 = new GroupableEntity(2, 'Bar', 'Group1');
$this->em->persist($item1);
$this->em->persist($item2);
$choiceList = new EntityChoiceList(
$this->em,
self::GROUPABLE_CLASS,
'name',
null,
array(
$item1,
$item2,
),
array(),
'child.that.does.not.exist'
);
$this->assertEquals(array(
1 => $item1,
2 => $item2,
), $choiceList->getChoices());
}
public function testInitShorthandEntityName()
{
$item1 = new SingleIntIdEntity(1, 'Foo');
$item2 = new SingleIntIdEntity(2, 'Bar');
$this->em->persist($item1);
$this->em->persist($item2);
$choiceList = new EntityChoiceList(
$this->em,
'SymfonyTestsDoctrine:SingleIntIdEntity'
);
$this->assertEquals(array(1, 2), $choiceList->getValuesForChoices(array($item1, $item2)));
}
public function testInitShorthandEntityName2()
{
$item1 = new SingleIntIdEntity(1, 'Foo');
$item2 = new SingleIntIdEntity(2, 'Bar');
$this->em->persist($item1);
$this->em->persist($item2);
$choiceList = new EntityChoiceList(
$this->em,
'SymfonyTestsDoctrine:SingleIntIdEntity'
);
$this->assertEquals(array(1, 2), $choiceList->getIndicesForChoices(array($item1, $item2)));
}
}

View File

@@ -0,0 +1,36 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;
if (!class_exists('Symfony\Component\Form\Tests\Extension\Core\ChoiceList\AbstractChoiceListTest')) {
return;
}
/**
* @author Bernhard Schussek <bschussek@gmail.com>
* @group legacy
*/
class LoadedEntityChoiceListCompositeIdTest extends AbstractEntityChoiceListCompositeIdTest
{
/**
* @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
*/
protected function createChoiceList()
{
$list = parent::createChoiceList();
// load list
$list->getChoices();
return $list;
}
}

View File

@@ -0,0 +1,37 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;
if (!class_exists('Symfony\Component\Form\Tests\Extension\Core\ChoiceList\AbstractChoiceListTest')) {
return;
}
/**
* @author Premi Giorgio <giosh94mhz@gmail.com>
* @author Bernhard Schussek <bschussek@gmail.com>
* @group legacy
*/
class LoadedEntityChoiceListSingleAssociationToIntIdTest extends AbstractEntityChoiceListSingleAssociationToIntIdTest
{
/**
* @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
*/
protected function createChoiceList()
{
$list = parent::createChoiceList();
// load list
$list->getChoices();
return $list;
}
}

View File

@@ -0,0 +1,36 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;
if (!class_exists('Symfony\Component\Form\Tests\Extension\Core\ChoiceList\AbstractChoiceListTest')) {
return;
}
/**
* @author Bernhard Schussek <bschussek@gmail.com>
* @group legacy
*/
class LoadedEntityChoiceListSingleIntIdTest extends AbstractEntityChoiceListSingleIntIdTest
{
/**
* @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
*/
protected function createChoiceList()
{
$list = parent::createChoiceList();
// load list
$list->getChoices();
return $list;
}
}

View File

@@ -0,0 +1,36 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;
if (!class_exists('Symfony\Component\Form\Tests\Extension\Core\ChoiceList\AbstractChoiceListTest')) {
return;
}
/**
* @author Bernhard Schussek <bschussek@gmail.com>
* @group legacy
*/
class LoadedEntityChoiceListSingleStringIdTest extends AbstractEntityChoiceListSingleStringIdTest
{
/**
* @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
*/
protected function createChoiceList()
{
$list = parent::createChoiceList();
// load list
$list->getChoices();
return $list;
}
}

View File

@@ -0,0 +1,183 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\Version;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Doctrine\Form\ChoiceList\ORMQueryBuilderLoader;
use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper;
class ORMQueryBuilderLoaderTest extends TestCase
{
/**
* @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException
* @group legacy
*/
public function testItOnlyWorksWithQueryBuilderOrClosure()
{
new ORMQueryBuilderLoader(new \stdClass());
}
/**
* @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException
* @group legacy
*/
public function testClosureRequiresTheEntityManager()
{
$closure = function () {};
new ORMQueryBuilderLoader($closure);
}
public function testIdentifierTypeIsStringArray()
{
$this->checkIdentifierType('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleStringIdEntity', Connection::PARAM_STR_ARRAY);
}
public function testIdentifierTypeIsIntegerArray()
{
$this->checkIdentifierType('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity', Connection::PARAM_INT_ARRAY);
}
protected function checkIdentifierType($classname, $expectedType)
{
$em = DoctrineTestHelper::createTestEntityManager();
$query = $this->getMockBuilder('QueryMock')
->setMethods(array('setParameter', 'getResult', 'getSql', '_doExecute'))
->getMock();
$query->expects($this->once())
->method('setParameter')
->with('ORMQueryBuilderLoader_getEntitiesByIds_id', array(1, 2), $expectedType)
->willReturn($query);
$qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
->setConstructorArgs(array($em))
->setMethods(array('getQuery'))
->getMock();
$qb->expects($this->once())
->method('getQuery')
->willReturn($query);
$qb->select('e')
->from($classname, 'e');
$loader = new ORMQueryBuilderLoader($qb);
$loader->getEntitiesByIds('id', array(1, 2));
}
public function testFilterNonIntegerValues()
{
$em = DoctrineTestHelper::createTestEntityManager();
$query = $this->getMockBuilder('QueryMock')
->setMethods(array('setParameter', 'getResult', 'getSql', '_doExecute'))
->getMock();
$query->expects($this->once())
->method('setParameter')
->with('ORMQueryBuilderLoader_getEntitiesByIds_id', array(1, 2, 3, '9223372036854775808'), Connection::PARAM_INT_ARRAY)
->willReturn($query);
$qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
->setConstructorArgs(array($em))
->setMethods(array('getQuery'))
->getMock();
$qb->expects($this->once())
->method('getQuery')
->willReturn($query);
$qb->select('e')
->from('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity', 'e');
$loader = new ORMQueryBuilderLoader($qb);
$loader->getEntitiesByIds('id', array(1, '', 2, 3, 'foo', '9223372036854775808'));
}
/**
* @dataProvider provideGuidEntityClasses
*/
public function testFilterEmptyUuids($entityClass)
{
$em = DoctrineTestHelper::createTestEntityManager();
$query = $this->getMockBuilder('QueryMock')
->setMethods(array('setParameter', 'getResult', 'getSql', '_doExecute'))
->getMock();
$query->expects($this->once())
->method('setParameter')
->with('ORMQueryBuilderLoader_getEntitiesByIds_id', array('71c5fd46-3f16-4abb-bad7-90ac1e654a2d', 'b98e8e11-2897-44df-ad24-d2627eb7f499'), Connection::PARAM_STR_ARRAY)
->willReturn($query);
$qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
->setConstructorArgs(array($em))
->setMethods(array('getQuery'))
->getMock();
$qb->expects($this->once())
->method('getQuery')
->willReturn($query);
$qb->select('e')
->from($entityClass, 'e');
$loader = new ORMQueryBuilderLoader($qb);
$loader->getEntitiesByIds('id', array('71c5fd46-3f16-4abb-bad7-90ac1e654a2d', '', 'b98e8e11-2897-44df-ad24-d2627eb7f499'));
}
public function testEmbeddedIdentifierName()
{
if (Version::compare('2.5.0') > 0) {
$this->markTestSkipped('Applicable only for Doctrine >= 2.5.0');
return;
}
$em = DoctrineTestHelper::createTestEntityManager();
$query = $this->getMockBuilder('QueryMock')
->setMethods(array('setParameter', 'getResult', 'getSql', '_doExecute'))
->getMock();
$query->expects($this->once())
->method('setParameter')
->with('ORMQueryBuilderLoader_getEntitiesByIds_id_value', array(1, 2, 3), Connection::PARAM_INT_ARRAY)
->willReturn($query);
$qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
->setConstructorArgs(array($em))
->setMethods(array('getQuery'))
->getMock();
$qb->expects($this->once())
->method('getQuery')
->willReturn($query);
$qb->select('e')
->from('Symfony\Bridge\Doctrine\Tests\Fixtures\EmbeddedIdentifierEntity', 'e');
$loader = new ORMQueryBuilderLoader($qb);
$loader->getEntitiesByIds('id.value', array(1, '', 2, 3, 'foo'));
}
public function provideGuidEntityClasses()
{
return array(
array('Symfony\Bridge\Doctrine\Tests\Fixtures\GuidIdEntity'),
array('Symfony\Bridge\Doctrine\Tests\Fixtures\UuidIdEntity'),
);
}
}

View File

@@ -0,0 +1,28 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;
if (!class_exists('Symfony\Component\Form\Tests\Extension\Core\ChoiceList\AbstractChoiceListTest')) {
return;
}
/**
* @author Bernhard Schussek <bschussek@gmail.com>
* @group legacy
*/
class UnloadedEntityChoiceListCompositeIdTest extends AbstractEntityChoiceListCompositeIdTest
{
public function testGetIndicesForValuesIgnoresNonExistingValues()
{
$this->markTestSkipped('Non-existing values are not detected for unloaded choice lists.');
}
}

View File

@@ -0,0 +1,37 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;
use Symfony\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList;
use Symfony\Bridge\Doctrine\Form\ChoiceList\ORMQueryBuilderLoader;
if (!class_exists('Symfony\Component\Form\Tests\Extension\Core\ChoiceList\AbstractChoiceListTest')) {
return;
}
/**
* @author Bernhard Schussek <bschussek@gmail.com>
* @group legacy
*/
class UnloadedEntityChoiceListCompositeIdWithQueryBuilderTest extends UnloadedEntityChoiceListCompositeIdTest
{
/**
* @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
*/
protected function createChoiceList()
{
$qb = $this->em->createQueryBuilder()->select('s')->from($this->getEntityClass(), 's');
$loader = new ORMQueryBuilderLoader($qb);
return new EntityChoiceList($this->em, $this->getEntityClass(), null, $loader);
}
}

View File

@@ -0,0 +1,37 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;
if (!class_exists('Symfony\Component\Form\Tests\Extension\Core\ChoiceList\AbstractChoiceListTest')) {
return;
}
/**
* @author Premi Giorgio <giosh94mhz@gmail.com>
* @author Bernhard Schussek <bschussek@gmail.com>
* @group legacy
*/
class UnloadedEntityChoiceListSingleAssociationToIntIdTest extends AbstractEntityChoiceListSingleAssociationToIntIdTest
{
public function testGetIndicesForValuesIgnoresNonExistingValues()
{
$this->markTestSkipped('Non-existing values are not detected for unloaded choice lists.');
}
/**
* @group legacy
*/
public function testLegacyGetIndicesForValuesIgnoresNonExistingValues()
{
$this->markTestSkipped('Non-existing values are not detected for unloaded choice lists.');
}
}

View File

@@ -0,0 +1,38 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;
use Symfony\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList;
use Symfony\Bridge\Doctrine\Form\ChoiceList\ORMQueryBuilderLoader;
if (!class_exists('Symfony\Component\Form\Tests\Extension\Core\ChoiceList\AbstractChoiceListTest')) {
return;
}
/**
* @author Premi Giorgio <giosh94mhz@gmail.com>
* @author Bernhard Schussek <bschussek@gmail.com>
* @group legacy
*/
class UnloadedEntityChoiceListSingleAssociationToIntIdWithQueryBuilderTest extends UnloadedEntityChoiceListSingleAssociationToIntIdTest
{
/**
* @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
*/
protected function createChoiceList()
{
$qb = $this->em->createQueryBuilder()->select('s')->from($this->getEntityClass(), 's');
$loader = new ORMQueryBuilderLoader($qb);
return new EntityChoiceList($this->em, $this->getEntityClass(), null, $loader);
}
}

View File

@@ -0,0 +1,28 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;
if (!class_exists('Symfony\Component\Form\Tests\Extension\Core\ChoiceList\AbstractChoiceListTest')) {
return;
}
/**
* @author Bernhard Schussek <bschussek@gmail.com>
* @group legacy
*/
class UnloadedEntityChoiceListSingleIntIdTest extends AbstractEntityChoiceListSingleIntIdTest
{
public function testGetIndicesForValuesIgnoresNonExistingValues()
{
$this->markTestSkipped('Non-existing values are not detected for unloaded choice lists.');
}
}

View File

@@ -0,0 +1,37 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;
use Symfony\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList;
use Symfony\Bridge\Doctrine\Form\ChoiceList\ORMQueryBuilderLoader;
if (!class_exists('Symfony\Component\Form\Tests\Extension\Core\ChoiceList\AbstractChoiceListTest')) {
return;
}
/**
* @author Bernhard Schussek <bschussek@gmail.com>
* @group legacy
*/
class UnloadedEntityChoiceListSingleIntIdWithQueryBuilderTest extends UnloadedEntityChoiceListSingleIntIdTest
{
/**
* @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
*/
protected function createChoiceList()
{
$qb = $this->em->createQueryBuilder()->select('s')->from($this->getEntityClass(), 's');
$loader = new ORMQueryBuilderLoader($qb);
return new EntityChoiceList($this->em, $this->getEntityClass(), null, $loader);
}
}

View File

@@ -0,0 +1,28 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;
if (!class_exists('Symfony\Component\Form\Tests\Extension\Core\ChoiceList\AbstractChoiceListTest')) {
return;
}
/**
* @author Bernhard Schussek <bschussek@gmail.com>
* @group legacy
*/
class UnloadedEntityChoiceListSingleStringIdTest extends AbstractEntityChoiceListSingleStringIdTest
{
public function testGetIndicesForValuesIgnoresNonExistingValues()
{
$this->markTestSkipped('Non-existing values are not detected for unloaded choice lists.');
}
}

View File

@@ -0,0 +1,37 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;
use Symfony\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList;
use Symfony\Bridge\Doctrine\Form\ChoiceList\ORMQueryBuilderLoader;
if (!class_exists('Symfony\Component\Form\Tests\Extension\Core\ChoiceList\AbstractChoiceListTest')) {
return;
}
/**
* @author Bernhard Schussek <bschussek@gmail.com>
* @group legacy
*/
class UnloadedEntityChoiceListSingleStringIdWithQueryBuilderTest extends UnloadedEntityChoiceListSingleStringIdTest
{
/**
* @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
*/
protected function createChoiceList()
{
$qb = $this->em->createQueryBuilder()->select('s')->from($this->getEntityClass(), 's');
$loader = new ORMQueryBuilderLoader($qb);
return new EntityChoiceList($this->em, $this->getEntityClass(), null, $loader);
}
}

View File

@@ -0,0 +1,92 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Form\DataTransformer;
use Doctrine\Common\Collections\ArrayCollection;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Doctrine\Form\DataTransformer\CollectionToArrayTransformer;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class CollectionToArrayTransformerTest extends TestCase
{
/**
* @var CollectionToArrayTransformer
*/
private $transformer;
protected function setUp()
{
$this->transformer = new CollectionToArrayTransformer();
}
public function testTransform()
{
$array = array(
2 => 'foo',
3 => 'bar',
);
$this->assertSame($array, $this->transformer->transform(new ArrayCollection($array)));
}
/**
* This test is needed for cases when getXxxs() in the entity returns the
* result of $collection->toArray(), in order to prevent modifications of
* the inner collection.
*
* See https://github.com/symfony/symfony/pull/9308
*/
public function testTransformArray()
{
$array = array(
2 => 'foo',
3 => 'bar',
);
$this->assertSame($array, $this->transformer->transform($array));
}
public function testTransformNull()
{
$this->assertSame(array(), $this->transformer->transform(null));
}
/**
* @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
*/
public function testTransformExpectsArrayOrCollection()
{
$this->transformer->transform('Foo');
}
public function testReverseTransform()
{
$array = array(
2 => 'foo',
3 => 'bar',
);
$this->assertEquals(new ArrayCollection($array), $this->transformer->reverseTransform($array));
}
public function testReverseTransformEmpty()
{
$this->assertEquals(new ArrayCollection(), $this->transformer->reverseTransform(''));
}
public function testReverseTransformNull()
{
$this->assertEquals(new ArrayCollection(), $this->transformer->reverseTransform(null));
}
}

View File

@@ -0,0 +1,94 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Form;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Doctrine\Form\DoctrineOrmTypeGuesser;
use Symfony\Component\Form\Guess\Guess;
use Symfony\Component\Form\Guess\ValueGuess;
class DoctrineOrmTypeGuesserTest extends TestCase
{
/**
* @dataProvider requiredProvider
*/
public function testRequiredGuesser($classMetadata, $expected)
{
$this->assertEquals($expected, $this->getGuesser($classMetadata)->guessRequired('TestEntity', 'field'));
}
public function requiredProvider()
{
$return = array();
// Simple field, not nullable
$classMetadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')->disableOriginalConstructor()->getMock();
$classMetadata->fieldMappings['field'] = true;
$classMetadata->expects($this->once())->method('isNullable')->with('field')->will($this->returnValue(false));
$return[] = array($classMetadata, new ValueGuess(true, Guess::HIGH_CONFIDENCE));
// Simple field, nullable
$classMetadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')->disableOriginalConstructor()->getMock();
$classMetadata->fieldMappings['field'] = true;
$classMetadata->expects($this->once())->method('isNullable')->with('field')->will($this->returnValue(true));
$return[] = array($classMetadata, new ValueGuess(false, Guess::MEDIUM_CONFIDENCE));
// One-to-one, nullable (by default)
$classMetadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')->disableOriginalConstructor()->getMock();
$classMetadata->expects($this->once())->method('isAssociationWithSingleJoinColumn')->with('field')->will($this->returnValue(true));
$mapping = array('joinColumns' => array(array()));
$classMetadata->expects($this->once())->method('getAssociationMapping')->with('field')->will($this->returnValue($mapping));
$return[] = array($classMetadata, new ValueGuess(false, Guess::HIGH_CONFIDENCE));
// One-to-one, nullable (explicit)
$classMetadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')->disableOriginalConstructor()->getMock();
$classMetadata->expects($this->once())->method('isAssociationWithSingleJoinColumn')->with('field')->will($this->returnValue(true));
$mapping = array('joinColumns' => array(array('nullable' => true)));
$classMetadata->expects($this->once())->method('getAssociationMapping')->with('field')->will($this->returnValue($mapping));
$return[] = array($classMetadata, new ValueGuess(false, Guess::HIGH_CONFIDENCE));
// One-to-one, not nullable
$classMetadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')->disableOriginalConstructor()->getMock();
$classMetadata->expects($this->once())->method('isAssociationWithSingleJoinColumn')->with('field')->will($this->returnValue(true));
$mapping = array('joinColumns' => array(array('nullable' => false)));
$classMetadata->expects($this->once())->method('getAssociationMapping')->with('field')->will($this->returnValue($mapping));
$return[] = array($classMetadata, new ValueGuess(true, Guess::HIGH_CONFIDENCE));
// One-to-many, no clue
$classMetadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')->disableOriginalConstructor()->getMock();
$classMetadata->expects($this->once())->method('isAssociationWithSingleJoinColumn')->with('field')->will($this->returnValue(false));
$return[] = array($classMetadata, null);
return $return;
}
private function getGuesser(ClassMetadata $classMetadata)
{
$em = $this->getMockBuilder('Doctrine\Common\Persistence\ObjectManager')->getMock();
$em->expects($this->once())->method('getClassMetaData')->with('TestEntity')->will($this->returnValue($classMetadata));
$registry = $this->getMockBuilder('Doctrine\Common\Persistence\ManagerRegistry')->getMock();
$registry->expects($this->once())->method('getManagers')->will($this->returnValue(array($em)));
return new DoctrineOrmTypeGuesser($registry);
}
}

View File

@@ -0,0 +1,139 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Form\Type;
use Doctrine\ORM\Tools\SchemaTool;
use Symfony\Bridge\Doctrine\Form\DoctrineOrmExtension;
use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper;
use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity;
use Symfony\Component\Form\Extension\Core\CoreExtension;
use Symfony\Component\Form\Test\FormPerformanceTestCase;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class EntityTypePerformanceTest extends FormPerformanceTestCase
{
const ENTITY_CLASS = 'Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity';
/**
* @var \Doctrine\ORM\EntityManager
*/
private $em;
protected function getExtensions()
{
$manager = $this->getMockBuilder('Doctrine\Common\Persistence\ManagerRegistry')->getMock();
$manager->expects($this->any())
->method('getManager')
->will($this->returnValue($this->em));
$manager->expects($this->any())
->method('getManagerForClass')
->will($this->returnValue($this->em));
return array(
new CoreExtension(),
new DoctrineOrmExtension($manager),
);
}
protected function setUp()
{
$this->em = DoctrineTestHelper::createTestEntityManager();
parent::setUp();
$schemaTool = new SchemaTool($this->em);
$classes = array(
$this->em->getClassMetadata(self::ENTITY_CLASS),
);
try {
$schemaTool->dropSchema($classes);
} catch (\Exception $e) {
}
try {
$schemaTool->createSchema($classes);
} catch (\Exception $e) {
}
$ids = range(1, 300);
foreach ($ids as $id) {
$name = 65 + (int) \chr($id % 57);
$this->em->persist(new SingleIntIdEntity($id, $name));
}
$this->em->flush();
}
/**
* This test case is realistic in collection forms where each
* row contains the same entity field.
*
* @group benchmark
*/
public function testCollapsedEntityField()
{
$this->setMaxRunningTime(1);
for ($i = 0; $i < 40; ++$i) {
$form = $this->factory->create('Symfony\Bridge\Doctrine\Form\Type\EntityType', null, array(
'class' => self::ENTITY_CLASS,
));
// force loading of the choice list
$form->createView();
}
}
/**
* @group benchmark
*/
public function testCollapsedEntityFieldWithChoices()
{
$choices = $this->em->createQuery('SELECT c FROM '.self::ENTITY_CLASS.' c')->getResult();
$this->setMaxRunningTime(1);
for ($i = 0; $i < 40; ++$i) {
$form = $this->factory->create('Symfony\Bridge\Doctrine\Form\Type\EntityType', null, array(
'class' => self::ENTITY_CLASS,
'choices' => $choices,
));
// force loading of the choice list
$form->createView();
}
}
/**
* @group benchmark
*/
public function testCollapsedEntityFieldWithPreferredChoices()
{
$choices = $this->em->createQuery('SELECT c FROM '.self::ENTITY_CLASS.' c')->getResult();
$this->setMaxRunningTime(1);
for ($i = 0; $i < 40; ++$i) {
$form = $this->factory->create('Symfony\Bridge\Doctrine\Form\Type\EntityType', null, array(
'class' => self::ENTITY_CLASS,
'preferred_choices' => $choices,
));
// force loading of the choice list
$form->createView();
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,31 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\HttpFoundation;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Doctrine\HttpFoundation\DbalSessionHandler;
/**
* Test class for DbalSessionHandler.
*
* @author Drak <drak@zikula.org>
*/
class DbalSessionHandlerTest extends TestCase
{
public function testConstruct()
{
$connection = $this->getMockBuilder('Doctrine\DBAL\Connection')->disableOriginalConstructor()->getMock();
$handler = new DbalSessionHandler($connection);
$this->assertInstanceOf('Symfony\Bridge\Doctrine\HttpFoundation\DbalSessionHandler', $handler);
}
}

View File

@@ -0,0 +1,169 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Logger;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Doctrine\Logger\DbalLogger;
class DbalLoggerTest extends TestCase
{
/**
* @dataProvider getLogFixtures
*/
public function testLog($sql, $params, $logParams)
{
$logger = $this->getMockBuilder('Psr\\Log\\LoggerInterface')->getMock();
$dbalLogger = $this
->getMockBuilder('Symfony\\Bridge\\Doctrine\\Logger\\DbalLogger')
->setConstructorArgs(array($logger, null))
->setMethods(array('log'))
->getMock()
;
$dbalLogger
->expects($this->once())
->method('log')
->with($sql, $logParams)
;
$dbalLogger->startQuery($sql, $params);
}
public function getLogFixtures()
{
return array(
array('SQL', null, array()),
array('SQL', array(), array()),
array('SQL', array('foo' => 'bar'), array('foo' => 'bar')),
array('SQL', array('foo' => "\x7F\xFF"), array('foo' => DbalLogger::BINARY_DATA_VALUE)),
array('SQL', array('foo' => "bar\x7F\xFF"), array('foo' => DbalLogger::BINARY_DATA_VALUE)),
array('SQL', array('foo' => ''), array('foo' => '')),
);
}
public function testLogNonUtf8()
{
$logger = $this->getMockBuilder('Psr\\Log\\LoggerInterface')->getMock();
$dbalLogger = $this
->getMockBuilder('Symfony\\Bridge\\Doctrine\\Logger\\DbalLogger')
->setConstructorArgs(array($logger, null))
->setMethods(array('log'))
->getMock()
;
$dbalLogger
->expects($this->once())
->method('log')
->with('SQL', array('utf8' => 'foo', 'nonutf8' => DbalLogger::BINARY_DATA_VALUE))
;
$dbalLogger->startQuery('SQL', array(
'utf8' => 'foo',
'nonutf8' => "\x7F\xFF",
));
}
public function testLogNonUtf8Array()
{
$logger = $this->getMockBuilder('Psr\\Log\\LoggerInterface')->getMock();
$dbalLogger = $this
->getMockBuilder('Symfony\\Bridge\\Doctrine\\Logger\\DbalLogger')
->setConstructorArgs(array($logger, null))
->setMethods(array('log'))
->getMock()
;
$dbalLogger
->expects($this->once())
->method('log')
->with('SQL', array(
'utf8' => 'foo',
array(
'nonutf8' => DbalLogger::BINARY_DATA_VALUE,
),
)
)
;
$dbalLogger->startQuery('SQL', array(
'utf8' => 'foo',
array(
'nonutf8' => "\x7F\xFF",
),
));
}
public function testLogLongString()
{
$logger = $this->getMockBuilder('Psr\\Log\\LoggerInterface')->getMock();
$dbalLogger = $this
->getMockBuilder('Symfony\\Bridge\\Doctrine\\Logger\\DbalLogger')
->setConstructorArgs(array($logger, null))
->setMethods(array('log'))
->getMock()
;
$testString = 'abc';
$shortString = str_pad('', DbalLogger::MAX_STRING_LENGTH, $testString);
$longString = str_pad('', DbalLogger::MAX_STRING_LENGTH + 1, $testString);
$dbalLogger
->expects($this->once())
->method('log')
->with('SQL', array('short' => $shortString, 'long' => substr($longString, 0, DbalLogger::MAX_STRING_LENGTH - 6).' [...]'))
;
$dbalLogger->startQuery('SQL', array(
'short' => $shortString,
'long' => $longString,
));
}
public function testLogUTF8LongString()
{
$logger = $this->getMockBuilder('Psr\\Log\\LoggerInterface')->getMock();
$dbalLogger = $this
->getMockBuilder('Symfony\\Bridge\\Doctrine\\Logger\\DbalLogger')
->setConstructorArgs(array($logger, null))
->setMethods(array('log'))
->getMock()
;
$testStringArray = array('é', 'á', 'ű', 'ő', 'ú', 'ö', 'ü', 'ó', 'í');
$testStringCount = \count($testStringArray);
$shortString = '';
$longString = '';
for ($i = 1; $i <= DbalLogger::MAX_STRING_LENGTH; ++$i) {
$shortString .= $testStringArray[$i % $testStringCount];
$longString .= $testStringArray[$i % $testStringCount];
}
$longString .= $testStringArray[$i % $testStringCount];
$dbalLogger
->expects($this->once())
->method('log')
->with('SQL', array('short' => $shortString, 'long' => mb_substr($longString, 0, DbalLogger::MAX_STRING_LENGTH - 6, 'UTF-8').' [...]'))
;
$dbalLogger->startQuery('SQL', array(
'short' => $shortString,
'long' => $longString,
));
}
}

View File

@@ -0,0 +1,163 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\PropertyInfo;
use Doctrine\DBAL\Types\Type as DBALType;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\Setup;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Doctrine\PropertyInfo\DoctrineExtractor;
use Symfony\Component\PropertyInfo\Type;
/**
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class DoctrineExtractorTest extends TestCase
{
/**
* @var DoctrineExtractor
*/
private $extractor;
protected function setUp()
{
$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__.\DIRECTORY_SEPARATOR.'Fixtures'), true);
$entityManager = EntityManager::create(array('driver' => 'pdo_sqlite'), $config);
if (!DBALType::hasType('foo')) {
DBALType::addType('foo', 'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineFooType');
$entityManager->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('custom_foo', 'foo');
}
$this->extractor = new DoctrineExtractor($entityManager->getMetadataFactory());
}
public function testGetProperties()
{
$this->assertEquals(
array(
'id',
'guid',
'time',
'json',
'simpleArray',
'float',
'decimal',
'bool',
'binary',
'customFoo',
'bigint',
'foo',
'bar',
'indexedBar',
'indexedFoo',
),
$this->extractor->getProperties('Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineDummy')
);
}
public function testGetPropertiesWithEmbedded()
{
if (!class_exists('Doctrine\ORM\Mapping\Embedded')) {
$this->markTestSkipped('@Embedded is not available in Doctrine ORM lower than 2.5.');
}
$this->assertEquals(
array(
'id',
'embedded',
),
$this->extractor->getProperties('Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineWithEmbedded')
);
}
/**
* @dataProvider typesProvider
*/
public function testExtract($property, array $type = null)
{
$this->assertEquals($type, $this->extractor->getTypes('Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineDummy', $property, array()));
}
public function testExtractWithEmbedded()
{
if (!class_exists('Doctrine\ORM\Mapping\Embedded')) {
$this->markTestSkipped('@Embedded is not available in Doctrine ORM lower than 2.5.');
}
$expectedTypes = array(new Type(
Type::BUILTIN_TYPE_OBJECT,
false,
'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineEmbeddable'
));
$actualTypes = $this->extractor->getTypes(
'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineWithEmbedded',
'embedded',
array()
);
$this->assertEquals($expectedTypes, $actualTypes);
}
public function typesProvider()
{
return array(
array('id', array(new Type(Type::BUILTIN_TYPE_INT))),
array('guid', array(new Type(Type::BUILTIN_TYPE_STRING))),
array('bigint', array(new Type(Type::BUILTIN_TYPE_STRING))),
array('float', array(new Type(Type::BUILTIN_TYPE_FLOAT))),
array('decimal', array(new Type(Type::BUILTIN_TYPE_STRING))),
array('bool', array(new Type(Type::BUILTIN_TYPE_BOOL))),
array('binary', array(new Type(Type::BUILTIN_TYPE_RESOURCE))),
array('json', array(new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true))),
array('foo', array(new Type(Type::BUILTIN_TYPE_OBJECT, true, 'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineRelation'))),
array('bar', array(new Type(
Type::BUILTIN_TYPE_OBJECT,
false,
'Doctrine\Common\Collections\Collection',
true,
new Type(Type::BUILTIN_TYPE_INT),
new Type(Type::BUILTIN_TYPE_OBJECT, false, 'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineRelation')
))),
array('indexedBar', array(new Type(
Type::BUILTIN_TYPE_OBJECT,
false,
'Doctrine\Common\Collections\Collection',
true,
new Type(Type::BUILTIN_TYPE_STRING),
new Type(Type::BUILTIN_TYPE_OBJECT, false, 'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineRelation')
))),
array('indexedFoo', array(new Type(
Type::BUILTIN_TYPE_OBJECT,
false,
'Doctrine\Common\Collections\Collection',
true,
new Type(Type::BUILTIN_TYPE_STRING),
new Type(Type::BUILTIN_TYPE_OBJECT, false, 'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineRelation')
))),
array('simpleArray', array(new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_STRING)))),
array('customFoo', null),
array('notMapped', null),
);
}
public function testGetPropertiesCatchException()
{
$this->assertNull($this->extractor->getProperties('Not\Exist'));
}
public function testGetTypesCatchException()
{
$this->assertNull($this->extractor->getTypes('Not\Exist', 'baz'));
}
}

View File

@@ -0,0 +1,105 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\ManyToMany;
use Doctrine\ORM\Mapping\ManyToOne;
use Doctrine\ORM\Mapping\OneToMany;
/**
* @Entity
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class DoctrineDummy
{
/**
* @Id
* @Column(type="smallint")
*/
public $id;
/**
* @ManyToOne(targetEntity="DoctrineRelation")
*/
public $foo;
/**
* @ManyToMany(targetEntity="DoctrineRelation")
*/
public $bar;
/**
* @ManyToMany(targetEntity="DoctrineRelation", indexBy="rguid")
*/
protected $indexedBar;
/**
* @OneToMany(targetEntity="DoctrineRelation", mappedBy="foo", indexBy="foo")
*/
protected $indexedFoo;
/**
* @Column(type="guid")
*/
protected $guid;
/**
* @Column(type="time")
*/
private $time;
/**
* @Column(type="json_array")
*/
private $json;
/**
* @Column(type="simple_array")
*/
private $simpleArray;
/**
* @Column(type="float")
*/
private $float;
/**
* @Column(type="decimal", precision=10, scale=2)
*/
private $decimal;
/**
* @Column(type="boolean")
*/
private $bool;
/**
* @Column(type="binary")
*/
private $binary;
/**
* @Column(type="custom_foo")
*/
private $customFoo;
/**
* @Column(type="bigint")
*/
private $bigint;
public $notMapped;
}

View File

@@ -0,0 +1,28 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Embeddable;
/**
* @Embeddable
*
* @author Udaltsov Valentin <udaltsov.valentin@gmail.com>
*/
class DoctrineEmbeddable
{
/**
* @Column(type="string")
*/
protected $field;
}

View File

@@ -0,0 +1,84 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\Type;
/**
* @author Teoh Han Hui <teohhanhui@gmail.com>
*/
class DoctrineFooType extends Type
{
/**
* Type name.
*/
const NAME = 'foo';
/**
* {@inheritdoc}
*/
public function getName()
{
return self::NAME;
}
/**
* {@inheritdoc}
*/
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
return $platform->getClobTypeDeclarationSQL(array());
}
/**
* {@inheritdoc}
*/
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
if (null === $value) {
return;
}
if (!$value instanceof Foo) {
throw new ConversionException(sprintf('Expected %s, got %s', 'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\Foo', \gettype($value)));
}
return $foo->bar;
}
/**
* {@inheritdoc}
*/
public function convertToPHPValue($value, AbstractPlatform $platform)
{
if (null === $value) {
return;
}
if (!\is_string($value)) {
throw ConversionException::conversionFailed($value, self::NAME);
}
$foo = new Foo();
$foo->bar = $value;
return $foo;
}
/**
* {@inheritdoc}
*/
public function requiresSQLCommentHint(AbstractPlatform $platform)
{
return true;
}
}

View File

@@ -0,0 +1,42 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\ManyToOne;
/**
* @Entity
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class DoctrineRelation
{
/**
* @Id
* @Column(type="smallint")
*/
public $id;
/**
* @Column(type="guid")
*/
protected $rguid;
/**
* @Column(type="guid")
* @ManyToOne(targetEntity="DoctrineDummy", inversedBy="indexedFoo")
*/
protected $foo;
}

View File

@@ -0,0 +1,36 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Embedded;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Id;
/**
* @Entity
*
* @author Udaltsov Valentin <udaltsov.valentin@gmail.com>
*/
class DoctrineWithEmbedded
{
/**
* @Id
* @Column(type="smallint")
*/
public $id;
/**
* @Embedded(class="DoctrineEmbeddable")
*/
protected $embedded;
}

View File

@@ -0,0 +1,23 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures;
/**
* @author Teoh Han Hui <teohhanhui@gmail.com>
*/
class Foo
{
/**
* @var string
*/
public $bar;
}

View File

@@ -0,0 +1,245 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Security\User;
use Doctrine\ORM\Tools\SchemaTool;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Doctrine\Security\User\EntityUserProvider;
use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper;
use Symfony\Bridge\Doctrine\Tests\Fixtures\User;
class EntityUserProviderTest extends TestCase
{
public function testRefreshUserGetsUserByPrimaryKey()
{
$em = DoctrineTestHelper::createTestEntityManager();
$this->createSchema($em);
$user1 = new User(1, 1, 'user1');
$user2 = new User(1, 2, 'user2');
$em->persist($user1);
$em->persist($user2);
$em->flush();
$provider = new EntityUserProvider($this->getManager($em), 'Symfony\Bridge\Doctrine\Tests\Fixtures\User', 'name');
// try to change the user identity
$user1->name = 'user2';
$this->assertSame($user1, $provider->refreshUser($user1));
}
public function testLoadUserByUsername()
{
$em = DoctrineTestHelper::createTestEntityManager();
$this->createSchema($em);
$user = new User(1, 1, 'user1');
$em->persist($user);
$em->flush();
$provider = new EntityUserProvider($this->getManager($em), 'Symfony\Bridge\Doctrine\Tests\Fixtures\User', 'name');
$this->assertSame($user, $provider->loadUserByUsername('user1'));
}
public function testLoadUserByUsernameWithUserLoaderRepositoryAndWithoutProperty()
{
$user = new User(1, 1, 'user1');
$repository = $this->getMockBuilder('Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface')
->disableOriginalConstructor()
->getMock();
$repository
->expects($this->once())
->method('loadUserByUsername')
->with('user1')
->willReturn($user);
$em = $this->getMockBuilder('Doctrine\ORM\EntityManager')
->disableOriginalConstructor()
->getMock();
$em
->expects($this->once())
->method('getRepository')
->with('Symfony\Bridge\Doctrine\Tests\Fixtures\User')
->willReturn($repository);
$provider = new EntityUserProvider($this->getManager($em), 'Symfony\Bridge\Doctrine\Tests\Fixtures\User');
$this->assertSame($user, $provider->loadUserByUsername('user1'));
}
/**
* @group legacy
* @expectedDeprecation Implementing Symfony\Component\Security\Core\User\UserProviderInterface in a Doctrine repository when using the entity provider is deprecated since Symfony 2.8 and will not be supported in 3.0. Make the repository implement Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface instead.
*/
public function testLoadUserByUsernameWithUserProviderRepositoryAndWithoutProperty()
{
$user = new User(1, 1, 'user1');
$repository = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserProviderInterface')
->disableOriginalConstructor()
->getMock();
$repository
->expects($this->once())
->method('loadUserByUsername')
->with('user1')
->willReturn($user);
$em = $this->getMockBuilder('Doctrine\ORM\EntityManager')
->disableOriginalConstructor()
->getMock();
$em
->expects($this->once())
->method('getRepository')
->with('Symfony\Bridge\Doctrine\Tests\Fixtures\User')
->willReturn($repository);
$provider = new EntityUserProvider($this->getManager($em), 'Symfony\Bridge\Doctrine\Tests\Fixtures\User');
$this->assertSame($user, $provider->loadUserByUsername('user1'));
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage You must either make the "Symfony\Bridge\Doctrine\Tests\Fixtures\User" entity Doctrine Repository ("Doctrine\ORM\EntityRepository") implement "Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface" or set the "property" option in the corresponding entity provider configuration.
*/
public function testLoadUserByUsernameWithNonUserLoaderRepositoryAndWithoutProperty()
{
$em = DoctrineTestHelper::createTestEntityManager();
$this->createSchema($em);
$user = new User(1, 1, 'user1');
$em->persist($user);
$em->flush();
$provider = new EntityUserProvider($this->getManager($em), 'Symfony\Bridge\Doctrine\Tests\Fixtures\User');
$provider->loadUserByUsername('user1');
}
public function testRefreshUserRequiresId()
{
$em = DoctrineTestHelper::createTestEntityManager();
$user1 = new User(null, null, 'user1');
$provider = new EntityUserProvider($this->getManager($em), 'Symfony\Bridge\Doctrine\Tests\Fixtures\User', 'name');
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}(
'InvalidArgumentException',
'You cannot refresh a user from the EntityUserProvider that does not contain an identifier. The user object has to be serialized with its own identifier mapped by Doctrine'
);
$provider->refreshUser($user1);
}
public function testRefreshInvalidUser()
{
$em = DoctrineTestHelper::createTestEntityManager();
$this->createSchema($em);
$user1 = new User(1, 1, 'user1');
$em->persist($user1);
$em->flush();
$provider = new EntityUserProvider($this->getManager($em), 'Symfony\Bridge\Doctrine\Tests\Fixtures\User', 'name');
$user2 = new User(1, 2, 'user2');
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}(
'Symfony\Component\Security\Core\Exception\UsernameNotFoundException',
'User with id {"id1":1,"id2":2} not found'
);
$provider->refreshUser($user2);
}
public function testSupportProxy()
{
$em = DoctrineTestHelper::createTestEntityManager();
$this->createSchema($em);
$user1 = new User(1, 1, 'user1');
$em->persist($user1);
$em->flush();
$em->clear();
$provider = new EntityUserProvider($this->getManager($em), 'Symfony\Bridge\Doctrine\Tests\Fixtures\User', 'name');
$user2 = $em->getReference('Symfony\Bridge\Doctrine\Tests\Fixtures\User', array('id1' => 1, 'id2' => 1));
$this->assertTrue($provider->supportsClass(\get_class($user2)));
}
public function testLoadUserByUserNameShouldLoadUserWhenProperInterfaceProvided()
{
$repository = $this->getMockBuilder('\Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface')->getMock();
$repository->expects($this->once())
->method('loadUserByUsername')
->with('name')
->willReturn(
$this->getMockBuilder('\Symfony\Component\Security\Core\User\UserInterface')->getMock()
);
$provider = new EntityUserProvider(
$this->getManager($this->getObjectManager($repository)),
'Symfony\Bridge\Doctrine\Tests\Fixtures\User'
);
$provider->loadUserByUsername('name');
}
/**
* @expectedException \InvalidArgumentException
*/
public function testLoadUserByUserNameShouldDeclineInvalidInterface()
{
$repository = $this->getMockBuilder('\Symfony\Component\Security\Core\User\AdvancedUserInterface')->getMock();
$provider = new EntityUserProvider(
$this->getManager($this->getObjectManager($repository)),
'Symfony\Bridge\Doctrine\Tests\Fixtures\User'
);
$provider->loadUserByUsername('name');
}
private function getManager($em, $name = null)
{
$manager = $this->getMockBuilder('Doctrine\Common\Persistence\ManagerRegistry')->getMock();
$manager->expects($this->any())
->method('getManager')
->with($this->equalTo($name))
->will($this->returnValue($em));
return $manager;
}
private function getObjectManager($repository)
{
$em = $this->getMockBuilder('\Doctrine\Common\Persistence\ObjectManager')
->setMethods(array('getClassMetadata', 'getRepository'))
->getMockForAbstractClass();
$em->expects($this->any())
->method('getRepository')
->willReturn($repository);
return $em;
}
private function createSchema($em)
{
$schemaTool = new SchemaTool($em);
$schemaTool->createSchema(array(
$em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\User'),
));
}
}

View File

@@ -0,0 +1,26 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Validator\Constraints;
use Symfony\Component\Validator\Validation;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
* @group legacy
*/
class LegacyUniqueEntityValidatorLegacyApiTest extends UniqueEntityValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5_BC;
}
}

View File

@@ -0,0 +1,553 @@
<?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.
*/
namespace Symfony\Bridge\Doctrine\Tests\Validator\Constraints;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\Persistence\ObjectRepository;
use Doctrine\ORM\Tools\SchemaTool;
use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper;
use Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity;
use Symfony\Bridge\Doctrine\Tests\Fixtures\DoubleNameEntity;
use Symfony\Bridge\Doctrine\Tests\Fixtures\DoubleNullableNameEntity;
use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntityValidator;
use Symfony\Component\Validator\Tests\Constraints\AbstractConstraintValidatorTest;
use Symfony\Component\Validator\Validation;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class UniqueEntityValidatorTest extends AbstractConstraintValidatorTest
{
const EM_NAME = 'foo';
/**
* @var ObjectManager
*/
protected $em;
/**
* @var ManagerRegistry
*/
protected $registry;
/**
* @var ObjectRepository
*/
protected $repository;
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function setUp()
{
$this->em = DoctrineTestHelper::createTestEntityManager();
$this->registry = $this->createRegistryMock($this->em);
$this->createSchema($this->em);
parent::setUp();
}
protected function createRegistryMock(ObjectManager $em = null)
{
$registry = $this->getMockBuilder('Doctrine\Common\Persistence\ManagerRegistry')->getMock();
$registry->expects($this->any())
->method('getManager')
->with($this->equalTo(self::EM_NAME))
->will($this->returnValue($em));
return $registry;
}
protected function createRepositoryMock()
{
$repository = $this->getMockBuilder('Doctrine\Common\Persistence\ObjectRepository')
->setMethods(array('findByCustom', 'find', 'findAll', 'findOneBy', 'findBy', 'getClassName'))
->getMock()
;
return $repository;
}
protected function createEntityManagerMock($repositoryMock)
{
$em = $this->getMockBuilder('Doctrine\Common\Persistence\ObjectManager')
->getMock()
;
$em->expects($this->any())
->method('getRepository')
->will($this->returnValue($repositoryMock))
;
$classMetadata = $this->getMockBuilder('Doctrine\Common\Persistence\Mapping\ClassMetadata')->getMock();
$classMetadata
->expects($this->any())
->method('hasField')
->will($this->returnValue(true))
;
$reflParser = $this->getMockBuilder('Doctrine\Common\Reflection\StaticReflectionParser')
->disableOriginalConstructor()
->getMock()
;
$refl = $this->getMockBuilder('Doctrine\Common\Reflection\StaticReflectionProperty')
->setConstructorArgs(array($reflParser, 'property-name'))
->setMethods(array('getValue'))
->getMock()
;
$refl
->expects($this->any())
->method('getValue')
->will($this->returnValue(true))
;
$classMetadata->reflFields = array('name' => $refl);
$em->expects($this->any())
->method('getClassMetadata')
->will($this->returnValue($classMetadata))
;
return $em;
}
protected function createValidator()
{
return new UniqueEntityValidator($this->registry);
}
private function createSchema(ObjectManager $em)
{
$schemaTool = new SchemaTool($em);
$schemaTool->createSchema(array(
$em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity'),
$em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\DoubleNameEntity'),
$em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\DoubleNullableNameEntity'),
$em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity'),
$em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity'),
));
}
/**
* This is a functional test as there is a large integration necessary to get the validator working.
*/
public function testValidateUniqueness()
{
$constraint = new UniqueEntity(array(
'message' => 'myMessage',
'fields' => array('name'),
'em' => self::EM_NAME,
));
$entity1 = new SingleIntIdEntity(1, 'Foo');
$entity2 = new SingleIntIdEntity(2, 'Foo');
$this->validator->validate($entity1, $constraint);
$this->assertNoViolation();
$this->em->persist($entity1);
$this->em->flush();
$this->validator->validate($entity1, $constraint);
$this->assertNoViolation();
$this->validator->validate($entity2, $constraint);
$this->buildViolation('myMessage')
->atPath('property.path.name')
->setInvalidValue('Foo')
->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
->assertRaised();
}
public function testValidateCustomErrorPath()
{
$constraint = new UniqueEntity(array(
'message' => 'myMessage',
'fields' => array('name'),
'em' => self::EM_NAME,
'errorPath' => 'bar',
));
$entity1 = new SingleIntIdEntity(1, 'Foo');
$entity2 = new SingleIntIdEntity(2, 'Foo');
$this->em->persist($entity1);
$this->em->flush();
$this->validator->validate($entity2, $constraint);
$this->buildViolation('myMessage')
->atPath('property.path.bar')
->setInvalidValue('Foo')
->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
->assertRaised();
}
public function testValidateUniquenessWithNull()
{
$constraint = new UniqueEntity(array(
'message' => 'myMessage',
'fields' => array('name'),
'em' => self::EM_NAME,
));
$entity1 = new SingleIntIdEntity(1, null);
$entity2 = new SingleIntIdEntity(2, null);
$this->em->persist($entity1);
$this->em->persist($entity2);
$this->em->flush();
$this->validator->validate($entity1, $constraint);
$this->assertNoViolation();
}
public function testValidateUniquenessWithIgnoreNullDisabled()
{
$constraint = new UniqueEntity(array(
'message' => 'myMessage',
'fields' => array('name', 'name2'),
'em' => self::EM_NAME,
'ignoreNull' => false,
));
$entity1 = new DoubleNameEntity(1, 'Foo', null);
$entity2 = new DoubleNameEntity(2, 'Foo', null);
$this->validator->validate($entity1, $constraint);
$this->assertNoViolation();
$this->em->persist($entity1);
$this->em->flush();
$this->validator->validate($entity1, $constraint);
$this->assertNoViolation();
$this->validator->validate($entity2, $constraint);
$this->buildViolation('myMessage')
->atPath('property.path.name')
->setInvalidValue('Foo')
->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
->assertRaised();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testAllConfiguredFieldsAreCheckedOfBeingMappedByDoctrineWithIgnoreNullEnabled()
{
$constraint = new UniqueEntity(array(
'message' => 'myMessage',
'fields' => array('name', 'name2'),
'em' => self::EM_NAME,
'ignoreNull' => true,
));
$entity1 = new SingleIntIdEntity(1, null);
$this->validator->validate($entity1, $constraint);
}
public function testNoValidationIfFirstFieldIsNullAndNullValuesAreIgnored()
{
$constraint = new UniqueEntity(array(
'message' => 'myMessage',
'fields' => array('name', 'name2'),
'em' => self::EM_NAME,
'ignoreNull' => true,
));
$entity1 = new DoubleNullableNameEntity(1, null, 'Foo');
$entity2 = new DoubleNullableNameEntity(2, null, 'Foo');
$this->validator->validate($entity1, $constraint);
$this->assertNoViolation();
$this->em->persist($entity1);
$this->em->flush();
$this->validator->validate($entity1, $constraint);
$this->assertNoViolation();
$this->validator->validate($entity2, $constraint);
$this->assertNoViolation();
}
public function testValidateUniquenessWithValidCustomErrorPath()
{
$constraint = new UniqueEntity(array(
'message' => 'myMessage',
'fields' => array('name', 'name2'),
'em' => self::EM_NAME,
'errorPath' => 'name2',
));
$entity1 = new DoubleNameEntity(1, 'Foo', 'Bar');
$entity2 = new DoubleNameEntity(2, 'Foo', 'Bar');
$this->validator->validate($entity1, $constraint);
$this->assertNoViolation();
$this->em->persist($entity1);
$this->em->flush();
$this->validator->validate($entity1, $constraint);
$this->assertNoViolation();
$this->validator->validate($entity2, $constraint);
$this->buildViolation('myMessage')
->atPath('property.path.name2')
->setInvalidValue('Bar')
->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
->assertRaised();
}
public function testValidateUniquenessUsingCustomRepositoryMethod()
{
$constraint = new UniqueEntity(array(
'message' => 'myMessage',
'fields' => array('name'),
'em' => self::EM_NAME,
'repositoryMethod' => 'findByCustom',
));
$repository = $this->createRepositoryMock();
$repository->expects($this->once())
->method('findByCustom')
->will($this->returnValue(array()))
;
$this->em = $this->createEntityManagerMock($repository);
$this->registry = $this->createRegistryMock($this->em);
$this->validator = $this->createValidator();
$this->validator->initialize($this->context);
$entity1 = new SingleIntIdEntity(1, 'foo');
$this->validator->validate($entity1, $constraint);
$this->assertNoViolation();
}
public function testValidateUniquenessWithUnrewoundArray()
{
$constraint = new UniqueEntity(array(
'message' => 'myMessage',
'fields' => array('name'),
'em' => self::EM_NAME,
'repositoryMethod' => 'findByCustom',
));
$entity = new SingleIntIdEntity(1, 'foo');
$repository = $this->createRepositoryMock();
$repository->expects($this->once())
->method('findByCustom')
->will(
$this->returnCallback(function () use ($entity) {
$returnValue = array(
$entity,
);
next($returnValue);
return $returnValue;
})
)
;
$this->em = $this->createEntityManagerMock($repository);
$this->registry = $this->createRegistryMock($this->em);
$this->validator = $this->createValidator();
$this->validator->initialize($this->context);
$this->validator->validate($entity, $constraint);
$this->assertNoViolation();
}
/**
* @dataProvider resultTypesProvider
*/
public function testValidateResultTypes($entity1, $result)
{
$constraint = new UniqueEntity(array(
'message' => 'myMessage',
'fields' => array('name'),
'em' => self::EM_NAME,
'repositoryMethod' => 'findByCustom',
));
$repository = $this->createRepositoryMock();
$repository->expects($this->once())
->method('findByCustom')
->will($this->returnValue($result))
;
$this->em = $this->createEntityManagerMock($repository);
$this->registry = $this->createRegistryMock($this->em);
$this->validator = $this->createValidator();
$this->validator->initialize($this->context);
$this->validator->validate($entity1, $constraint);
$this->assertNoViolation();
}
public function resultTypesProvider()
{
$entity = new SingleIntIdEntity(1, 'foo');
return array(
array($entity, array($entity)),
array($entity, new \ArrayIterator(array($entity))),
array($entity, new ArrayCollection(array($entity))),
);
}
public function testAssociatedEntity()
{
$constraint = new UniqueEntity(array(
'message' => 'myMessage',
'fields' => array('single'),
'em' => self::EM_NAME,
));
$entity1 = new SingleIntIdEntity(1, 'foo');
$associated = new AssociationEntity();
$associated->single = $entity1;
$associated2 = new AssociationEntity();
$associated2->single = $entity1;
$this->em->persist($entity1);
$this->em->persist($associated);
$this->em->flush();
$this->validator->validate($associated, $constraint);
$this->assertNoViolation();
$this->em->persist($associated2);
$this->em->flush();
$this->validator->validate($associated2, $constraint);
$this->buildViolation('myMessage')
->atPath('property.path.single')
->setInvalidValue($entity1)
->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
->assertRaised();
}
public function testAssociatedEntityWithNull()
{
$constraint = new UniqueEntity(array(
'message' => 'myMessage',
'fields' => array('single'),
'em' => self::EM_NAME,
'ignoreNull' => false,
));
$associated = new AssociationEntity();
$associated->single = null;
$this->em->persist($associated);
$this->em->flush();
$this->validator->validate($associated, $constraint);
$this->assertNoViolation();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
* @expectedExceptionMessage Object manager "foo" does not exist.
*/
public function testDedicatedEntityManagerNullObject()
{
$constraint = new UniqueEntity(array(
'message' => 'myMessage',
'fields' => array('name'),
'em' => self::EM_NAME,
));
$this->em = null;
$this->registry = $this->createRegistryMock($this->em);
$this->validator = $this->createValidator();
$this->validator->initialize($this->context);
$entity = new SingleIntIdEntity(1, null);
$this->validator->validate($entity, $constraint);
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
* @expectedExceptionMessage Unable to find the object manager associated with an entity of class "Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity"
*/
public function testEntityManagerNullObject()
{
$constraint = new UniqueEntity(array(
'message' => 'myMessage',
'fields' => array('name'),
// no "em" option set
));
$this->em = null;
$this->registry = $this->createRegistryMock($this->em);
$this->validator = $this->createValidator();
$this->validator->initialize($this->context);
$entity = new SingleIntIdEntity(1, null);
$this->validator->validate($entity, $constraint);
}
public function testValidateUniquenessOnNullResult()
{
$repository = $this->createRepositoryMock();
$repository
->method('find')
->will($this->returnValue(null))
;
$this->em = $this->createEntityManagerMock($repository);
$this->registry = $this->createRegistryMock($this->em);
$this->validator = $this->createValidator();
$this->validator->initialize($this->context);
$constraint = new UniqueEntity(array(
'message' => 'myMessage',
'fields' => array('name'),
'em' => self::EM_NAME,
));
$entity = new SingleIntIdEntity(1, null);
$this->em->persist($entity);
$this->em->flush();
$this->validator->validate($entity, $constraint);
$this->assertNoViolation();
}
}