@@ -23,11 +20,10 @@
{% block menu %}
-
+
Elastica
{{ collector.querycount }}
- {{ '%0.0f'|format(collector.time * 1000) }} ms
{% endblock %}
diff --git a/Serializer/Callback.php b/Serializer/Callback.php
index 61da997..9fe7064 100644
--- a/Serializer/Callback.php
+++ b/Serializer/Callback.php
@@ -8,7 +8,7 @@ use JMS\Serializer\SerializerInterface;
class Callback
{
protected $serializer;
- protected $groups = array();
+ protected $groups;
protected $version;
public function setSerializer($serializer)
@@ -23,8 +23,10 @@ class Callback
{
$this->groups = $groups;
- if (!empty($this->groups) && !$this->serializer instanceof SerializerInterface) {
- throw new \RuntimeException('Setting serialization groups requires using "JMS\Serializer\Serializer".');
+ if ($this->groups) {
+ if (!$this->serializer instanceof SerializerInterface) {
+ throw new \RuntimeException('Setting serialization groups requires using "JMS\Serializer\Serializer".');
+ }
}
}
@@ -32,16 +34,18 @@ class Callback
{
$this->version = $version;
- if ($this->version && !$this->serializer instanceof SerializerInterface) {
- throw new \RuntimeException('Setting serialization version requires using "JMS\Serializer\Serializer".');
+ if ($this->version) {
+ if (!$this->serializer instanceof SerializerInterface) {
+ throw new \RuntimeException('Setting serialization version requires using "JMS\Serializer\Serializer".');
+ }
}
}
public function serialize($object)
{
- $context = $this->serializer instanceof SerializerInterface ? SerializationContext::create()->enableMaxDepthChecks() : array();
+ $context = $this->serializer instanceof SerializerInterface ? new SerializationContext() : array();
- if (!empty($this->groups)) {
+ if ($this->groups) {
$context->setGroups($this->groups);
}
diff --git a/Subscriber/PaginateElasticaQuerySubscriber.php b/Subscriber/PaginateElasticaQuerySubscriber.php
index 63f6cd0..0b7cfd6 100644
--- a/Subscriber/PaginateElasticaQuerySubscriber.php
+++ b/Subscriber/PaginateElasticaQuerySubscriber.php
@@ -32,17 +32,13 @@ class PaginateElasticaQuerySubscriber implements EventSubscriberInterface
if (null != $facets) {
$event->setCustomPaginationParameter('facets', $facets);
}
- $aggregations = $results->getAggregations();
- if (null != $aggregations) {
- $event->setCustomPaginationParameter('aggregations', $aggregations);
- }
$event->stopPropagation();
}
}
/**
- * Adds knp paging sort to query.
+ * Adds knp paging sort to query
*
* @param ItemsEvent $event
*/
@@ -74,7 +70,7 @@ class PaginateElasticaQuerySubscriber implements EventSubscriberInterface
public static function getSubscribedEvents()
{
return array(
- 'knp_pager.items' => array('items', 1),
+ 'knp_pager.items' => array('items', 1)
);
}
-}
+}
\ No newline at end of file
diff --git a/Tests/Command/ResetCommandTest.php b/Tests/Command/ResetCommandTest.php
index d63b380..b6548aa 100644
--- a/Tests/Command/ResetCommandTest.php
+++ b/Tests/Command/ResetCommandTest.php
@@ -2,6 +2,7 @@
namespace FOS\ElasticaBundle\Tests\Command;
+
use FOS\ElasticaBundle\Command\ResetCommand;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\NullOutput;
@@ -9,8 +10,8 @@ use Symfony\Component\DependencyInjection\Container;
class ResetCommandTest extends \PHPUnit_Framework_TestCase
{
- private $command;
private $resetter;
+
private $indexManager;
public function setup()
@@ -87,4 +88,4 @@ class ResetCommandTest extends \PHPUnit_Framework_TestCase
new NullOutput()
);
}
-}
+}
\ No newline at end of file
diff --git a/Tests/DependencyInjection/ConfigurationTest.php b/Tests/DependencyInjection/ConfigurationTest.php
index 062db5c..5919ea7 100644
--- a/Tests/DependencyInjection/ConfigurationTest.php
+++ b/Tests/DependencyInjection/ConfigurationTest.php
@@ -6,260 +6,145 @@ use FOS\ElasticaBundle\DependencyInjection\Configuration;
use Symfony\Component\Config\Definition\Processor;
/**
- * ConfigurationTest.
+ * ConfigurationTest
*/
class ConfigurationTest extends \PHPUnit_Framework_TestCase
{
/**
- * @var Processor
+ * @var Configuration
*/
- private $processor;
+ private $configuration;
public function setUp()
{
- $this->processor = new Processor();
+ $this->configuration = new Configuration(array());
}
- private function getConfigs(array $configArray)
+ public function testEmptyConfigContainsFormatMappingOptionNode()
{
- $configuration = new Configuration(true);
+ $tree = $this->configuration->getConfigTree();
+ $children = $tree->getChildren();
+ $children = $children['indexes']->getPrototype()->getChildren();
+ $typeNodes = $children['types']->getPrototype()->getChildren();
+ $mappings = $typeNodes['mappings']->getPrototype()->getChildren();
- return $this->processor->processConfiguration($configuration, array($configArray));
+ $this->assertArrayHasKey('format', $mappings);
+ $this->assertInstanceOf('Symfony\Component\Config\Definition\ScalarNode', $mappings['format']);
+ $this->assertNull($mappings['format']->getDefaultValue());
}
- public function testUnconfiguredConfiguration()
+ public function testDynamicTemplateNodes()
{
- $configuration = $this->getConfigs(array());
+ $tree = $this->configuration->getConfigTree();
+ $children = $tree->getChildren();
+ $children = $children['indexes']->getPrototype()->getChildren();
+ $typeNodes = $children['types']->getPrototype()->getChildren();
+ $dynamicTemplates = $typeNodes['dynamic_templates']->getPrototype()->getChildren();
- $this->assertSame(array(
- 'clients' => array(),
- 'indexes' => array(),
- 'default_manager' => 'orm',
- ), $configuration);
+ $this->assertArrayHasKey('match', $dynamicTemplates);
+ $this->assertInstanceOf('Symfony\Component\Config\Definition\ScalarNode', $dynamicTemplates['match']);
+ $this->assertNull($dynamicTemplates['match']->getDefaultValue());
+
+ $this->assertArrayHasKey('match_mapping_type', $dynamicTemplates);
+ $this->assertInstanceOf('Symfony\Component\Config\Definition\ScalarNode', $dynamicTemplates['match_mapping_type']);
+ $this->assertNull($dynamicTemplates['match_mapping_type']->getDefaultValue());
+
+ $this->assertArrayHasKey('unmatch', $dynamicTemplates);
+ $this->assertInstanceOf('Symfony\Component\Config\Definition\ScalarNode', $dynamicTemplates['unmatch']);
+ $this->assertNull($dynamicTemplates['unmatch']->getDefaultValue());
+
+ $this->assertArrayHasKey('path_match', $dynamicTemplates);
+ $this->assertInstanceOf('Symfony\Component\Config\Definition\ScalarNode', $dynamicTemplates['path_match']);
+ $this->assertNull($dynamicTemplates['path_match']->getDefaultValue());
+
+ $this->assertArrayHasKey('path_unmatch', $dynamicTemplates);
+ $this->assertInstanceOf('Symfony\Component\Config\Definition\ScalarNode', $dynamicTemplates['path_unmatch']);
+ $this->assertNull($dynamicTemplates['path_unmatch']->getDefaultValue());
+
+ $this->assertArrayHasKey('match_pattern', $dynamicTemplates);
+ $this->assertInstanceOf('Symfony\Component\Config\Definition\ScalarNode', $dynamicTemplates['match_pattern']);
+ $this->assertNull($dynamicTemplates['match_pattern']->getDefaultValue());
+
+ $this->assertArrayHasKey('mapping', $dynamicTemplates);
+ $this->assertInstanceOf('Symfony\Component\Config\Definition\ArrayNode', $dynamicTemplates['mapping']);
}
- public function testClientConfiguration()
+ public function testDynamicTemplateMappingNodes()
{
- $configuration = $this->getConfigs(array(
- 'clients' => array(
- 'default' => array(
- 'url' => 'http://localhost:9200',
- ),
- 'clustered' => array(
- 'connections' => array(
- array(
- 'url' => 'http://es1:9200',
- 'headers' => array(
- 'Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==',
- ),
- ),
- array(
- 'url' => 'http://es2:9200',
- 'headers' => array(
- 'Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==',
- ),
- ),
- ),
- ),
- ),
- ));
+ $tree = $this->configuration->getConfigTree();
+ $children = $tree->getChildren();
+ $children = $children['indexes']->getPrototype()->getChildren();
+ $typeNodes = $children['types']->getPrototype()->getChildren();
+ $dynamicTemplates = $typeNodes['dynamic_templates']->getPrototype()->getChildren();
+ $mapping = $dynamicTemplates['mapping']->getChildren();
- $this->assertCount(2, $configuration['clients']);
- $this->assertCount(1, $configuration['clients']['default']['connections']);
- $this->assertCount(0, $configuration['clients']['default']['connections'][0]['headers']);
+ $this->assertArrayHasKey('type', $mapping);
+ $this->assertInstanceOf('Symfony\Component\Config\Definition\ScalarNode', $mapping['type']);
+ $this->assertSame('string', $mapping['type']->getDefaultValue());
- $this->assertCount(2, $configuration['clients']['clustered']['connections']);
- $this->assertEquals('http://es2:9200/', $configuration['clients']['clustered']['connections'][1]['url']);
- $this->assertCount(1, $configuration['clients']['clustered']['connections'][1]['headers']);
- $this->assertEquals('Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==', $configuration['clients']['clustered']['connections'][0]['headers'][0]);
- }
-
- public function testLogging()
- {
- $configuration = $this->getConfigs(array(
- 'clients' => array(
- 'logging_enabled' => array(
- 'url' => 'http://localhost:9200',
- 'logger' => true,
- ),
- 'logging_disabled' => array(
- 'url' => 'http://localhost:9200',
- 'logger' => false,
- ),
- 'logging_not_mentioned' => array(
- 'url' => 'http://localhost:9200',
- ),
- 'logging_custom' => array(
- 'url' => 'http://localhost:9200',
- 'logger' => 'custom.service',
- ),
- ),
- ));
-
- $this->assertCount(4, $configuration['clients']);
-
- $this->assertEquals('fos_elastica.logger', $configuration['clients']['logging_enabled']['connections'][0]['logger']);
- $this->assertFalse($configuration['clients']['logging_disabled']['connections'][0]['logger']);
- $this->assertEquals('fos_elastica.logger', $configuration['clients']['logging_not_mentioned']['connections'][0]['logger']);
- $this->assertEquals('custom.service', $configuration['clients']['logging_custom']['connections'][0]['logger']);
+ $this->assertArrayHasKey('index', $mapping);
+ $this->assertInstanceOf('Symfony\Component\Config\Definition\ScalarNode', $mapping['index']);
+ $this->assertNull($mapping['index']->getDefaultValue());
}
public function testSlashIsAddedAtTheEndOfServerUrl()
{
$config = array(
'clients' => array(
- 'default' => array('url' => 'http://www.github.com'),
+ 'default' => array(
+ 'url' => 'http://www.github.com',
+ ),
),
- );
- $configuration = $this->getConfigs($config);
+ );
+
+ $processor = new Processor();
- $this->assertEquals('http://www.github.com/', $configuration['clients']['default']['connections'][0]['url']);
+ $configuration = $processor->processConfiguration($this->configuration, array($config));
+
+ $this->assertEquals('http://www.github.com/', $configuration['clients']['default']['servers'][0]['url']);
}
- public function testTypeConfig()
+ public function testEmptyFieldsIndexIsUnset()
{
- $this->getConfigs(array(
- 'clients' => array(
- 'default' => array('url' => 'http://localhost:9200'),
- ),
+ $config = array(
'indexes' => array(
'test' => array(
- 'type_prototype' => array(
- 'index_analyzer' => 'custom_analyzer',
- 'persistence' => array(
- 'identifier' => 'ID',
- ),
- 'serializer' => array(
- 'groups' => array('Search'),
- 'version' => 1,
- ),
- ),
'types' => array(
'test' => array(
'mappings' => array(
- 'title' => array(),
- 'published' => array('type' => 'datetime'),
- 'body' => null,
- ),
- 'persistence' => array(
- 'listener' => array(
- 'logger' => true,
+ 'title' => array(
+ 'type' => 'string',
+ 'fields' => array(
+ 'autocomplete' => null
+ )
),
- ),
- ),
- 'test2' => array(
- 'mappings' => array(
- 'title' => null,
+ 'content' => null,
'children' => array(
'type' => 'nested',
- ),
- ),
- ),
- ),
- ),
- ),
- ));
- }
-
- public function testClientConfigurationNoUrl()
- {
- $configuration = $this->getConfigs(array(
- 'clients' => array(
- 'default' => array(
- 'host' => 'localhost',
- 'port' => 9200,
- ),
- ),
- ));
-
- $this->assertTrue(empty($configuration['clients']['default']['connections'][0]['url']));
- }
-
- public function testMappingsRenamedToProperties()
- {
- $configuration = $this->getConfigs(array(
- 'clients' => array(
- 'default' => array('url' => 'http://localhost:9200'),
- ),
- 'indexes' => array(
- 'test' => array(
- 'types' => array(
- 'test' => array(
- 'mappings' => array(
- 'title' => array(),
- 'published' => array('type' => 'datetime'),
- 'body' => null,
- ),
- ),
- ),
- ),
- ),
- ));
-
- $this->assertCount(3, $configuration['indexes']['test']['types']['test']['properties']);
- }
-
- public function testUnconfiguredType()
- {
- $configuration = $this->getConfigs(array(
- 'clients' => array(
- 'default' => array('url' => 'http://localhost:9200'),
- ),
- 'indexes' => array(
- 'test' => array(
- 'types' => array(
- 'test' => null,
- ),
- ),
- ),
- ));
-
- $this->assertArrayHasKey('properties', $configuration['indexes']['test']['types']['test']);
- }
-
- public function testNestedProperties()
- {
- $this->getConfigs(array(
- 'clients' => array(
- 'default' => array('url' => 'http://localhost:9200'),
- ),
- 'indexes' => array(
- 'test' => array(
- 'types' => array(
- 'user' => array(
- 'properties' => array(
- 'field1' => array(),
- ),
- 'persistence' => array(),
- ),
- 'user_profile' => array(
- '_parent' => array(
- 'type' => 'user',
- 'property' => 'owner',
- ),
- 'properties' => array(
- 'field1' => array(),
- 'field2' => array(
- 'type' => 'nested',
'properties' => array(
- 'nested_field1' => array(
- 'type' => 'integer',
+ 'title' => array(
+ 'type' => 'string',
+ 'fields' => array(
+ 'autocomplete' => null
+ )
),
- 'nested_field2' => array(
- 'type' => 'object',
- 'properties' => array(
- 'id' => array(
- 'type' => 'integer',
- ),
- ),
- ),
- ),
- ),
- ),
- ),
- ),
- ),
- ),
- ));
+ 'content' => null
+ )
+ )
+ )
+ )
+ )
+ )
+ )
+ );
+
+ $processor = new Processor();
+
+ $configuration = $processor->processConfiguration(new Configuration(array($config)), array($config));
+
+ $this->assertArrayNotHasKey('fields', $configuration['indexes']['test']['types']['test']['mappings']['content']);
+ $this->assertArrayHasKey('fields', $configuration['indexes']['test']['types']['test']['mappings']['title']);
+ $this->assertArrayNotHasKey('fields', $configuration['indexes']['test']['types']['test']['mappings']['children']['properties']['content']);
+ $this->assertArrayHasKey('fields', $configuration['indexes']['test']['types']['test']['mappings']['children']['properties']['title']);
}
}
diff --git a/Tests/DependencyInjection/FOSElasticaExtensionTest.php b/Tests/DependencyInjection/FOSElasticaExtensionTest.php
deleted file mode 100644
index 1bef2b6..0000000
--- a/Tests/DependencyInjection/FOSElasticaExtensionTest.php
+++ /dev/null
@@ -1,32 +0,0 @@
-setParameter('kernel.debug', true);
-
- $extension = new FOSElasticaExtension();
-
- $extension->load($config, $containerBuilder);
-
- $this->assertTrue($containerBuilder->hasDefinition('fos_elastica.object_persister.test_index.child_field'));
-
- $persisterCallDefinition = $containerBuilder->getDefinition('fos_elastica.object_persister.test_index.child_field');
-
- $arguments = $persisterCallDefinition->getArguments();
- $arguments = $arguments['index_3'];
-
- $this->assertArrayHasKey('_parent', $arguments);
- $this->assertEquals('parent_field', $arguments['_parent']['type']);
- }
-}
diff --git a/Tests/DependencyInjection/fixtures/config.yml b/Tests/DependencyInjection/fixtures/config.yml
deleted file mode 100644
index 5528d18..0000000
--- a/Tests/DependencyInjection/fixtures/config.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-fos_elastica:
- clients:
- default:
- url: http://localhost:9200
- indexes:
- test_index:
- client: default
- types:
- parent_field:
- mappings:
- text: ~
- persistence:
- driver: orm
- model: foo_model
- child_field:
- mappings:
- text: ~
- persistence:
- driver: orm
- model: foo_model
- _parent: { type: "parent_field", property: "parent" }
diff --git a/Tests/Doctrine/AbstractElasticaToModelTransformerTest.php b/Tests/Doctrine/AbstractElasticaToModelTransformerTest.php
deleted file mode 100644
index 1185e74..0000000
--- a/Tests/Doctrine/AbstractElasticaToModelTransformerTest.php
+++ /dev/null
@@ -1,62 +0,0 @@
-getMock(
- 'FOS\ElasticaBundle\Doctrine\ORM\ElasticaToModelTransformer',
- array('findByIdentifiers'),
- array($this->registry, $this->objectClass, array('ignore_missing' => true))
- );
-
- $transformer->setPropertyAccessor(PropertyAccess::createPropertyAccessor());
-
- $firstOrmResult = new \stdClass();
- $firstOrmResult->id = 1;
- $secondOrmResult = new \stdClass();
- $secondOrmResult->id = 3;
- $transformer->expects($this->once())
- ->method('findByIdentifiers')
- ->with(array(1, 2, 3))
- ->willReturn(array($firstOrmResult, $secondOrmResult));
-
- $firstElasticaResult = new Result(array('_id' => 1));
- $secondElasticaResult = new Result(array('_id' => 2));
- $thirdElasticaResult = new Result(array('_id' => 3));
-
- $hybridResults = $transformer->hybridTransform(array($firstElasticaResult, $secondElasticaResult, $thirdElasticaResult));
-
- $this->assertCount(2, $hybridResults);
- $this->assertEquals($firstOrmResult, $hybridResults[0]->getTransformed());
- $this->assertEquals($firstElasticaResult, $hybridResults[0]->getResult());
- $this->assertEquals($secondOrmResult, $hybridResults[1]->getTransformed());
- $this->assertEquals($thirdElasticaResult, $hybridResults[1]->getResult());
- }
-
- protected function setUp()
- {
- $this->registry = $this->getMockBuilder('Doctrine\Common\Persistence\ManagerRegistry')
- ->disableOriginalConstructor()
- ->getMock();
- }
-}
diff --git a/Tests/Doctrine/AbstractListenerTest.php b/Tests/Doctrine/AbstractListenerTest.php
index dcaf7d6..ee657f1 100644
--- a/Tests/Doctrine/AbstractListenerTest.php
+++ b/Tests/Doctrine/AbstractListenerTest.php
@@ -3,7 +3,7 @@
namespace FOS\ElasticaBundle\Tests\Doctrine;
/**
- * See concrete MongoDB/ORM instances of this abstract test.
+ * See concrete MongoDB/ORM instances of this abstract test
*
* @author Richard Miller
*/
@@ -11,12 +11,12 @@ abstract class ListenerTest extends \PHPUnit_Framework_TestCase
{
public function testObjectInsertedOnPersist()
{
- $entity = new Listener\Entity(1);
- $persister = $this->getMockPersister($entity, 'index', 'type');
- $eventArgs = $this->createLifecycleEventArgs($entity, $this->getMockObjectManager());
- $indexable = $this->getMockIndexable('index', 'type', $entity, true);
+ $persister = $this->getMockPersister();
- $listener = $this->createListener($persister, $indexable, array('indexName' => 'index', 'typeName' => 'type'));
+ $entity = new Listener\Entity(1);
+ $eventArgs = $this->createLifecycleEventArgs($entity, $this->getMockObjectManager());
+
+ $listener = $this->createListener($persister, get_class($entity), array());
$listener->postPersist($eventArgs);
$this->assertEquals($entity, current($listener->scheduledForInsertion));
@@ -28,14 +28,18 @@ abstract class ListenerTest extends \PHPUnit_Framework_TestCase
$listener->postFlush($eventArgs);
}
- public function testNonIndexableObjectNotInsertedOnPersist()
+ /**
+ * @dataProvider provideIsIndexableCallbacks
+ */
+ public function testNonIndexableObjectNotInsertedOnPersist($isIndexableCallback)
{
- $entity = new Listener\Entity(1);
- $persister = $this->getMockPersister($entity, 'index', 'type');
- $eventArgs = $this->createLifecycleEventArgs($entity, $this->getMockObjectManager());
- $indexable = $this->getMockIndexable('index', 'type', $entity, false);
+ $persister = $this->getMockPersister();
- $listener = $this->createListener($persister, $indexable, array('indexName' => 'index', 'typeName' => 'type'));
+ $entity = new Listener\Entity(1, false);
+ $eventArgs = $this->createLifecycleEventArgs($entity, $this->getMockObjectManager());
+
+ $listener = $this->createListener($persister, get_class($entity), array());
+ $listener->setIsIndexableCallback($isIndexableCallback);
$listener->postPersist($eventArgs);
$this->assertEmpty($listener->scheduledForInsertion);
@@ -50,12 +54,12 @@ abstract class ListenerTest extends \PHPUnit_Framework_TestCase
public function testObjectReplacedOnUpdate()
{
- $entity = new Listener\Entity(1);
- $persister = $this->getMockPersister($entity, 'index', 'type');
- $eventArgs = $this->createLifecycleEventArgs($entity, $this->getMockObjectManager());
- $indexable = $this->getMockIndexable('index', 'type', $entity, true);
+ $persister = $this->getMockPersister();
- $listener = $this->createListener($persister, $indexable, array('indexName' => 'index', 'typeName' => 'type'));
+ $entity = new Listener\Entity(1);
+ $eventArgs = $this->createLifecycleEventArgs($entity, $this->getMockObjectManager());
+
+ $listener = $this->createListener($persister, get_class($entity), array());
$listener->postUpdate($eventArgs);
$this->assertEquals($entity, current($listener->scheduledForUpdate));
@@ -69,15 +73,17 @@ abstract class ListenerTest extends \PHPUnit_Framework_TestCase
$listener->postFlush($eventArgs);
}
- public function testNonIndexableObjectRemovedOnUpdate()
+ /**
+ * @dataProvider provideIsIndexableCallbacks
+ */
+ public function testNonIndexableObjectRemovedOnUpdate($isIndexableCallback)
{
$classMetadata = $this->getMockClassMetadata();
$objectManager = $this->getMockObjectManager();
+ $persister = $this->getMockPersister();
- $entity = new Listener\Entity(1);
- $persister = $this->getMockPersister($entity, 'index', 'type');
+ $entity = new Listener\Entity(1, false);
$eventArgs = $this->createLifecycleEventArgs($entity, $objectManager);
- $indexable = $this->getMockIndexable('index', 'type', $entity, false);
$objectManager->expects($this->any())
->method('getClassMetadata')
@@ -89,7 +95,8 @@ abstract class ListenerTest extends \PHPUnit_Framework_TestCase
->with($entity, 'id')
->will($this->returnValue($entity->getId()));
- $listener = $this->createListener($persister, $indexable, array('indexName' => 'index', 'typeName' => 'type'));
+ $listener = $this->createListener($persister, get_class($entity), array());
+ $listener->setIsIndexableCallback($isIndexableCallback);
$listener->postUpdate($eventArgs);
$this->assertEmpty($listener->scheduledForUpdate);
@@ -108,11 +115,10 @@ abstract class ListenerTest extends \PHPUnit_Framework_TestCase
{
$classMetadata = $this->getMockClassMetadata();
$objectManager = $this->getMockObjectManager();
+ $persister = $this->getMockPersister();
$entity = new Listener\Entity(1);
- $persister = $this->getMockPersister($entity, 'index', 'type');
$eventArgs = $this->createLifecycleEventArgs($entity, $objectManager);
- $indexable = $this->getMockIndexable('index', 'type', $entity);
$objectManager->expects($this->any())
->method('getClassMetadata')
@@ -124,7 +130,7 @@ abstract class ListenerTest extends \PHPUnit_Framework_TestCase
->with($entity, 'id')
->will($this->returnValue($entity->getId()));
- $listener = $this->createListener($persister, $indexable, array('indexName' => 'index', 'typeName' => 'type'));
+ $listener = $this->createListener($persister, get_class($entity), array());
$listener->preRemove($eventArgs);
$this->assertEquals($entity->getId(), current($listener->scheduledForDeletion));
@@ -140,12 +146,11 @@ abstract class ListenerTest extends \PHPUnit_Framework_TestCase
{
$classMetadata = $this->getMockClassMetadata();
$objectManager = $this->getMockObjectManager();
+ $persister = $this->getMockPersister();
$entity = new Listener\Entity(1);
$entity->identifier = 'foo';
- $persister = $this->getMockPersister($entity, 'index', 'type');
$eventArgs = $this->createLifecycleEventArgs($entity, $objectManager);
- $indexable = $this->getMockIndexable('index', 'type', $entity);
$objectManager->expects($this->any())
->method('getClassMetadata')
@@ -157,7 +162,7 @@ abstract class ListenerTest extends \PHPUnit_Framework_TestCase
->with($entity, 'identifier')
->will($this->returnValue($entity->getId()));
- $listener = $this->createListener($persister, $indexable, array('identifier' => 'identifier', 'indexName' => 'index', 'typeName' => 'type'));
+ $listener = $this->createListener($persister, get_class($entity), array(), 'identifier');
$listener->preRemove($eventArgs);
$this->assertEquals($entity->identifier, current($listener->scheduledForDeletion));
@@ -169,18 +174,42 @@ abstract class ListenerTest extends \PHPUnit_Framework_TestCase
$listener->postFlush($eventArgs);
}
+ /**
+ * @dataProvider provideInvalidIsIndexableCallbacks
+ * @expectedException \RuntimeException
+ */
+ public function testInvalidIsIndexableCallbacks($isIndexableCallback)
+ {
+ $listener = $this->createListener($this->getMockPersister(), 'FOS\ElasticaBundle\Tests\Doctrine\Listener\Entity', array());
+ $listener->setIsIndexableCallback($isIndexableCallback);
+ }
+
+ public function provideInvalidIsIndexableCallbacks()
+ {
+ return array(
+ array('nonexistentEntityMethod'),
+ array(array(new Listener\IndexableDecider(), 'internalMethod')),
+ array(42),
+ array('entity.getIsIndexable() && nonexistentEntityFunction()'),
+ );
+ }
+
+ public function provideIsIndexableCallbacks()
+ {
+ return array(
+ array('getIsIndexable'),
+ array(array(new Listener\IndexableDecider(), 'isIndexable')),
+ array(function(Listener\Entity $entity) { return $entity->getIsIndexable(); }),
+ array('entity.getIsIndexable()')
+ );
+ }
+
abstract protected function getLifecycleEventArgsClass();
abstract protected function getListenerClass();
- /**
- * @return string
- */
abstract protected function getObjectManagerClass();
- /**
- * @return string
- */
abstract protected function getClassMetadataClass();
private function createLifecycleEventArgs()
@@ -211,59 +240,9 @@ abstract class ListenerTest extends \PHPUnit_Framework_TestCase
->getMock();
}
- /**
- * @param Listener\Entity $object
- * @param string $indexName
- * @param string $typeName
- */
- private function getMockPersister($object, $indexName, $typeName)
+ private function getMockPersister()
{
- $mock = $this->getMockBuilder('FOS\ElasticaBundle\Persister\ObjectPersister')
- ->disableOriginalConstructor()
- ->getMock();
-
- $mock->expects($this->any())
- ->method('handlesObject')
- ->with($object)
- ->will($this->returnValue(true));
-
- $index = $this->getMockBuilder('Elastica\Index')->disableOriginalConstructor()->getMock();
- $index->expects($this->any())
- ->method('getName')
- ->will($this->returnValue($indexName));
- $type = $this->getMockBuilder('Elastica\Type')->disableOriginalConstructor()->getMock();
- $type->expects($this->any())
- ->method('getName')
- ->will($this->returnValue($typeName));
- $type->expects($this->any())
- ->method('getIndex')
- ->will($this->returnValue($index));
-
- $mock->expects($this->any())
- ->method('getType')
- ->will($this->returnValue($type));
-
- return $mock;
- }
-
- /**
- * @param string $indexName
- * @param string $typeName
- * @param Listener\Entity $object
- * @param boolean $return
- */
- private function getMockIndexable($indexName, $typeName, $object, $return = null)
- {
- $mock = $this->getMock('FOS\ElasticaBundle\Provider\IndexableInterface');
-
- if (null !== $return) {
- $mock->expects($this->once())
- ->method('isObjectIndexable')
- ->with($indexName, $typeName, $object)
- ->will($this->returnValue($return));
- }
-
- return $mock;
+ return $this->getMock('FOS\ElasticaBundle\Persister\ObjectPersisterInterface');
}
}
@@ -272,18 +251,33 @@ namespace FOS\ElasticaBundle\Tests\Doctrine\Listener;
class Entity
{
private $id;
- public $identifier;
+ private $isIndexable;
- /**
- * @param integer $id
- */
- public function __construct($id)
+ public function __construct($id, $isIndexable = true)
{
$this->id = $id;
+ $this->isIndexable = $isIndexable;
}
public function getId()
{
return $this->id;
}
+
+ public function getIsIndexable()
+ {
+ return $this->isIndexable;
+ }
+}
+
+class IndexableDecider
+{
+ public function isIndexable(Entity $entity)
+ {
+ return $entity->getIsIndexable();
+ }
+
+ protected function internalMethod()
+ {
+ }
}
diff --git a/Tests/Doctrine/AbstractProviderTest.php b/Tests/Doctrine/AbstractProviderTest.php
index aa28a4c..2492eed 100644
--- a/Tests/Doctrine/AbstractProviderTest.php
+++ b/Tests/Doctrine/AbstractProviderTest.php
@@ -2,9 +2,6 @@
namespace FOS\ElasticaBundle\Tests\Doctrine;
-use Elastica\Bulk\ResponseSet;
-use Elastica\Response;
-
class AbstractProviderTest extends \PHPUnit_Framework_TestCase
{
private $objectClass;
@@ -12,25 +9,24 @@ class AbstractProviderTest extends \PHPUnit_Framework_TestCase
private $objectPersister;
private $options;
private $managerRegistry;
- private $indexable;
- private $sliceFetcher;
public function setUp()
{
- $this->objectClass = 'objectClass';
- $this->options = array('debug_logging' => true, 'indexName' => 'index', 'typeName' => 'type');
+ if (!interface_exists('Doctrine\Common\Persistence\ManagerRegistry')) {
+ $this->markTestSkipped('Doctrine Common is not available.');
+ }
- $this->objectPersister = $this->getMockObjectPersister();
- $this->managerRegistry = $this->getMockManagerRegistry();
- $this->objectManager = $this->getMockObjectManager();
- $this->indexable = $this->getMockIndexable();
+ $this->objectClass = 'objectClass';
+ $this->options = array();
- $this->managerRegistry->expects($this->any())
- ->method('getManagerForClass')
- ->with($this->objectClass)
- ->will($this->returnValue($this->objectManager));
+ $this->objectPersister = $this->getMockObjectPersister();
+ $this->managerRegistry = $this->getMockManagerRegistry();
+ $this->objectManager = $this->getMockObjectManager();
- $this->sliceFetcher = $this->getMockSliceFetcher();
+ $this->managerRegistry->expects($this->any())
+ ->method('getManagerForClass')
+ ->with($this->objectClass)
+ ->will($this->returnValue($this->objectManager));
}
/**
@@ -53,58 +49,6 @@ class AbstractProviderTest extends \PHPUnit_Framework_TestCase
->with($queryBuilder)
->will($this->returnValue($nbObjects));
- $this->indexable->expects($this->any())
- ->method('isObjectIndexable')
- ->with('index', 'type', $this->anything())
- ->will($this->returnValue(true));
-
- $previousSlice = array();
-
- foreach ($objectsByIteration as $i => $objects) {
- $offset = $objects[0] - 1;
-
- $this->sliceFetcher->expects($this->at($i))
- ->method('fetch')
- ->with($queryBuilder, $batchSize, $offset, $previousSlice, array('id'))
- ->will($this->returnValue($objects));
-
- $this->objectManager->expects($this->at($i))
- ->method('clear');
-
- $previousSlice = $objects;
- }
-
- $this->objectPersister->expects($this->exactly(count($objectsByIteration)))
- ->method('insertMany');
-
- $provider->populate();
- }
-
- /**
- * @dataProvider providePopulateIterations
- */
- public function testPopulateIterationsWithoutSliceFetcher($nbObjects, $objectsByIteration, $batchSize)
- {
- $this->options['batch_size'] = $batchSize;
-
- $provider = $this->getMockAbstractProvider(false);
-
- $queryBuilder = new \stdClass();
-
- $provider->expects($this->once())
- ->method('createQueryBuilder')
- ->will($this->returnValue($queryBuilder));
-
- $provider->expects($this->once())
- ->method('countObjects')
- ->with($queryBuilder)
- ->will($this->returnValue($nbObjects));
-
- $this->indexable->expects($this->any())
- ->method('isObjectIndexable')
- ->with('index', 'type', $this->anything())
- ->will($this->returnValue(true));
-
$providerInvocationOffset = 2;
foreach ($objectsByIteration as $i => $objects) {
@@ -115,13 +59,14 @@ class AbstractProviderTest extends \PHPUnit_Framework_TestCase
->with($queryBuilder, $batchSize, $offset)
->will($this->returnValue($objects));
+ $this->objectPersister->expects($this->at($i))
+ ->method('insertMany')
+ ->with($objects);
+
$this->objectManager->expects($this->at($i))
->method('clear');
}
- $this->objectPersister->expects($this->exactly(count($objectsByIteration)))
- ->method('insertMany');
-
$provider->populate();
}
@@ -130,7 +75,7 @@ class AbstractProviderTest extends \PHPUnit_Framework_TestCase
return array(
array(
100,
- array(range(1, 100)),
+ array(range(1,100)),
100,
),
array(
@@ -153,47 +98,16 @@ class AbstractProviderTest extends \PHPUnit_Framework_TestCase
->method('countObjects')
->will($this->returnValue($nbObjects));
- $this->sliceFetcher->expects($this->any())
- ->method('fetch')
+ $provider->expects($this->any())
+ ->method('fetchSlice')
->will($this->returnValue($objects));
- $this->indexable->expects($this->any())
- ->method('isObjectIndexable')
- ->with('index', 'type', $this->anything())
- ->will($this->returnValue(true));
-
$this->objectManager->expects($this->never())
->method('clear');
$provider->populate();
}
- public function testPopulateShouldClearObjectManagerForFilteredBatch()
- {
- $nbObjects = 1;
- $objects = array(1);
-
- $provider = $this->getMockAbstractProvider(true);
-
- $provider->expects($this->any())
- ->method('countObjects')
- ->will($this->returnValue($nbObjects));
-
- $this->sliceFetcher->expects($this->any())
- ->method('fetch')
- ->will($this->returnValue($objects));
-
- $this->indexable->expects($this->any())
- ->method('isObjectIndexable')
- ->with('index', 'type', $this->anything())
- ->will($this->returnValue(false));
-
- $this->objectManager->expects($this->once())
- ->method('clear');
-
- $provider->populate();
- }
-
public function testPopulateInvokesLoggerClosure()
{
$nbObjects = 1;
@@ -205,15 +119,10 @@ class AbstractProviderTest extends \PHPUnit_Framework_TestCase
->method('countObjects')
->will($this->returnValue($nbObjects));
- $this->sliceFetcher->expects($this->any())
- ->method('fetch')
+ $provider->expects($this->any())
+ ->method('fetchSlice')
->will($this->returnValue($objects));
- $this->indexable->expects($this->any())
- ->method('isObjectIndexable')
- ->with('index', 'type', $this->anything())
- ->will($this->returnValue(true));
-
$loggerClosureInvoked = false;
$loggerClosure = function () use (&$loggerClosureInvoked) {
$loggerClosureInvoked = true;
@@ -237,68 +146,29 @@ class AbstractProviderTest extends \PHPUnit_Framework_TestCase
->method('countObjects')
->will($this->returnValue($nbObjects));
- $this->sliceFetcher->expects($this->any())
- ->method('fetch')
+ $provider->expects($this->any())
+ ->method('fetchSlice')
->will($this->returnValue($objects));
- $this->indexable->expects($this->any())
- ->method('isObjectIndexable')
- ->with('index', 'type', $this->anything())
- ->will($this->returnValue(true));
-
$this->objectPersister->expects($this->any())
->method('insertMany')
->will($this->throwException($this->getMockBulkResponseException()));
$this->setExpectedException('Elastica\Exception\Bulk\ResponseException');
- $provider->populate(null, array('ignore_errors' => false));
- }
-
- public function testPopulateRunsIndexCallable()
- {
- $nbObjects = 2;
- $objects = array(1, 2);
-
- $provider = $this->getMockAbstractProvider();
- $provider->expects($this->any())
- ->method('countObjects')
- ->will($this->returnValue($nbObjects));
-
- $this->sliceFetcher->expects($this->any())
- ->method('fetch')
- ->will($this->returnValue($objects));
-
- $this->indexable->expects($this->at(0))
- ->method('isObjectIndexable')
- ->with('index', 'type', 1)
- ->will($this->returnValue(false));
- $this->indexable->expects($this->at(1))
- ->method('isObjectIndexable')
- ->with('index', 'type', 2)
- ->will($this->returnValue(true));
-
- $this->objectPersister->expects($this->once())
- ->method('insertMany')
- ->with(array(2));
-
- $provider->populate();
+ $provider->populate(null, array('ignore-errors' => false));
}
/**
- * @param boolean $setSliceFetcher Whether or not to set the slice fetcher.
- *
* @return \FOS\ElasticaBundle\Doctrine\AbstractProvider|\PHPUnit_Framework_MockObject_MockObject
*/
- private function getMockAbstractProvider($setSliceFetcher = true)
+ private function getMockAbstractProvider()
{
return $this->getMockForAbstractClass('FOS\ElasticaBundle\Doctrine\AbstractProvider', array(
$this->objectPersister,
- $this->indexable,
$this->objectClass,
$this->options,
$this->managerRegistry,
- $setSliceFetcher ? $this->sliceFetcher : null
));
}
@@ -307,9 +177,9 @@ class AbstractProviderTest extends \PHPUnit_Framework_TestCase
*/
private function getMockBulkResponseException()
{
- return $this->getMock('Elastica\Exception\Bulk\ResponseException', null, array(
- new ResponseSet(new Response(array()), array()),
- ));
+ return $this->getMockBuilder('Elastica\Exception\Bulk\ResponseException')
+ ->disableOriginalConstructor()
+ ->getMock();
}
/**
@@ -325,17 +195,7 @@ class AbstractProviderTest extends \PHPUnit_Framework_TestCase
*/
private function getMockObjectManager()
{
- $mock = $this->getMock(__NAMESPACE__.'\ObjectManager');
-
- $mock->expects($this->any())
- ->method('getClassMetadata')
- ->will($this->returnSelf());
-
- $mock->expects($this->any())
- ->method('getIdentifierFieldNames')
- ->will($this->returnValue(array('id')));
-
- return $mock;
+ return $this->getMock(__NAMESPACE__ . '\ObjectManager');
}
/**
@@ -345,22 +205,6 @@ class AbstractProviderTest extends \PHPUnit_Framework_TestCase
{
return $this->getMock('FOS\ElasticaBundle\Persister\ObjectPersisterInterface');
}
-
- /**
- * @return \FOS\ElasticaBundle\Provider\IndexableInterface|\PHPUnit_Framework_MockObject_MockObject
- */
- private function getMockIndexable()
- {
- return $this->getMock('FOS\ElasticaBundle\Provider\IndexableInterface');
- }
-
- /**
- * @return \FOS\ElasticaBundle\Doctrine\SliceFetcherInterface|\PHPUnit_Framework_MockObject_MockObject
- */
- private function getMockSliceFetcher()
- {
- return $this->getMock('FOS\ElasticaBundle\Doctrine\SliceFetcherInterface');
- }
}
/**
@@ -369,7 +213,5 @@ class AbstractProviderTest extends \PHPUnit_Framework_TestCase
*/
interface ObjectManager
{
- public function clear();
- public function getClassMetadata();
- public function getIdentifierFieldNames();
+ function clear();
}
diff --git a/Tests/Doctrine/ORM/ElasticaToModelTransformerTest.php b/Tests/Doctrine/ORM/ElasticaToModelTransformerTest.php
index 607aeef..14f3ffb 100644
--- a/Tests/Doctrine/ORM/ElasticaToModelTransformerTest.php
+++ b/Tests/Doctrine/ORM/ElasticaToModelTransformerTest.php
@@ -82,6 +82,13 @@ class ElasticaToModelTransformerTest extends \PHPUnit_Framework_TestCase
protected function setUp()
{
+ if (!interface_exists('Doctrine\Common\Persistence\ManagerRegistry')) {
+ $this->markTestSkipped('Doctrine Common is not present');
+ }
+ if (!class_exists('Doctrine\ORM\EntityManager')) {
+ $this->markTestSkipped('Doctrine Common is not present');
+ }
+
$this->registry = $this->getMockBuilder('Doctrine\Common\Persistence\ManagerRegistry')
->disableOriginalConstructor()
->getMock();
@@ -102,7 +109,7 @@ class ElasticaToModelTransformerTest extends \PHPUnit_Framework_TestCase
'findAll',
'findBy',
'findOneBy',
- 'getClassName',
+ 'getClassName'
));
$this->manager->expects($this->any())
diff --git a/Tests/Doctrine/ORM/ListenerTest.php b/Tests/Doctrine/ORM/ListenerTest.php
index 36cacc6..12a89b2 100644
--- a/Tests/Doctrine/ORM/ListenerTest.php
+++ b/Tests/Doctrine/ORM/ListenerTest.php
@@ -6,6 +6,13 @@ use FOS\ElasticaBundle\Tests\Doctrine\ListenerTest as BaseListenerTest;
class ListenerTest extends BaseListenerTest
{
+ public function setUp()
+ {
+ if (!class_exists('Doctrine\ORM\EntityManager')) {
+ $this->markTestSkipped('Doctrine ORM is not available.');
+ }
+ }
+
protected function getClassMetadataClass()
{
return 'Doctrine\ORM\Mapping\ClassMetadata';
diff --git a/Tests/Doctrine/RepositoryManagerTest.php b/Tests/Doctrine/RepositoryManagerTest.php
index 39f9c34..ce7b14b 100644
--- a/Tests/Doctrine/RepositoryManagerTest.php
+++ b/Tests/Doctrine/RepositoryManagerTest.php
@@ -4,19 +4,22 @@ namespace FOS\ElasticaBundle\Tests\Doctrine;
use FOS\ElasticaBundle\Doctrine\RepositoryManager;
-class CustomRepository
-{
-}
+class CustomRepository{}
-class Entity
-{
-}
+class Entity{}
/**
* @author Richard Miller
*/
class RepositoryManagerTest extends \PHPUnit_Framework_TestCase
{
+ public function setUp()
+ {
+ if (!interface_exists('Doctrine\Common\Persistence\ManagerRegistry')) {
+ $this->markTestSkipped('Doctrine Common is not available.');
+ }
+ }
+
public function testThatGetRepositoryReturnsDefaultRepository()
{
/** @var $finderMock \PHPUnit_Framework_MockObject_MockObject|\FOS\ElasticaBundle\Finder\TransformedFinder */
diff --git a/Tests/Elastica/ClientTest.php b/Tests/Elastica/LoggingClientTest.php
similarity index 51%
rename from Tests/Elastica/ClientTest.php
rename to Tests/Elastica/LoggingClientTest.php
index 158b553..0b3e71d 100644
--- a/Tests/Elastica/ClientTest.php
+++ b/Tests/Elastica/LoggingClientTest.php
@@ -4,12 +4,36 @@ namespace FOS\ElasticaBundle\Tests\Client;
use Elastica\Request;
use Elastica\Transport\Null as NullTransport;
+use FOS\ElasticaBundle\Elastica\LoggingClient;
-class ClientTest extends \PHPUnit_Framework_TestCase
+class LoggingClientTest extends \PHPUnit_Framework_TestCase
{
+ public function testOverriddenElasticaMethods()
+ {
+ $resultTransformer = $this->getMockBuilder('FOS\ElasticaBundle\Transformer\CombinedResultTransformer')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $client = new LoggingClient(array(), null, $resultTransformer);
+ $index = $client->getIndex('index');
+ $type = $index->getType('type');
+
+ $this->assertInstanceOf('FOS\ElasticaBundle\Elastica\TransformingIndex', $index);
+ $this->assertInstanceOf('FOS\ElasticaBundle\Elastica\TransformingType', $type);
+ }
+
+ public function testGetResultTransformer()
+ {
+ $resultTransformer = $this->getMockBuilder('FOS\ElasticaBundle\Transformer\CombinedResultTransformer')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $client = new LoggingClient(array(), null, $resultTransformer);
+
+ $this->assertSame($resultTransformer, $client->getResultTransformer());
+ }
+
public function testRequestsAreLogged()
{
- $transport = new NullTransport();
+ $transport = new NullTransport;
$connection = $this->getMock('Elastica\Connection');
$connection->expects($this->any())->method('getTransportObject')->will($this->returnValue($transport));
@@ -28,7 +52,8 @@ class ClientTest extends \PHPUnit_Framework_TestCase
$this->isType('array')
);
- $client = $this->getMockBuilder('FOS\ElasticaBundle\Elastica\Client')
+ $client = $this->getMockBuilder('FOS\ElasticaBundle\Elastica\LoggingClient')
+ ->disableOriginalConstructor()
->setMethods(array('getConnection'))
->getMock();
diff --git a/Tests/Elastica/TransformingIndexTest.php b/Tests/Elastica/TransformingIndexTest.php
new file mode 100644
index 0000000..e652119
--- /dev/null
+++ b/Tests/Elastica/TransformingIndexTest.php
@@ -0,0 +1,42 @@
+index->createSearch();
+
+ $this->assertInstanceOf('FOS\ElasticaBundle\Elastica\TransformingSearch', $search);
+ }
+
+ public function testOverrideName()
+ {
+ $this->assertEquals('testindex', $this->index->getName());
+
+ $this->index->overrideName('newindex');
+
+ $this->assertEquals('newindex', $this->index->getName());
+ }
+
+ protected function setUp()
+ {
+ $this->client = $this->getMockBuilder('FOS\ElasticaBundle\Elastica\LoggingClient')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $this->index = new TransformingIndex($this->client, 'testindex');
+ }
+}
diff --git a/Tests/Elastica/TransformingResultSetTest.php b/Tests/Elastica/TransformingResultSetTest.php
new file mode 100644
index 0000000..9b9b38a
--- /dev/null
+++ b/Tests/Elastica/TransformingResultSetTest.php
@@ -0,0 +1,42 @@
+ array(
+ 'hits' => array(
+ array(),
+ array(),
+ array(),
+ )
+ )));
+ $query = new Query();
+ $transformer = $this->getMockBuilder('FOS\ElasticaBundle\Transformer\CombinedResultTransformer')
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $resultSet = new TransformingResultSet($response, $query, $transformer);
+
+ $this->assertCount(3, $resultSet);
+ $this->assertInstanceOf('FOS\ElasticaBundle\Elastica\TransformingResult', $resultSet[0]);
+
+ $transformer->expects($this->once())
+ ->method('transform')
+ ->with($resultSet->getResults());
+
+ $resultSet->transform();
+ $resultSet->transform();
+
+ $this->assertSame(array(
+ 0 => null, 1 => null, 2 => null
+ ), $resultSet->getTransformed());
+ }
+}
diff --git a/Tests/Elastica/TransformingResultTest.php b/Tests/Elastica/TransformingResultTest.php
new file mode 100644
index 0000000..286b7d1
--- /dev/null
+++ b/Tests/Elastica/TransformingResultTest.php
@@ -0,0 +1,22 @@
+getMockBuilder('FOS\ElasticaBundle\Elastica\TransformingResultSet')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $result = new TransformingResult(array(), $resultSet);
+
+ $resultSet->expects($this->exactly(2))
+ ->method('transform');
+
+ $result->getTransformed();
+ $result->getTransformed();
+ }
+}
diff --git a/Tests/FOSElasticaBundleTest.php b/Tests/FOSElasticaBundleTest.php
index c9513db..2bfc7f9 100644
--- a/Tests/FOSElasticaBundleTest.php
+++ b/Tests/FOSElasticaBundleTest.php
@@ -3,20 +3,37 @@
namespace FOS\ElasticaBundle\Tests\Resetter;
use FOS\ElasticaBundle\FOSElasticaBundle;
+use Symfony\Component\DependencyInjection\Compiler\PassConfig;
class FOSElasticaBundleTest extends \PHPUnit_Framework_TestCase
{
public function testCompilerPassesAreRegistered()
{
+ $passes = array(
+ array (
+ 'FOS\ElasticaBundle\DependencyInjection\Compiler\RegisterProvidersPass',
+ PassConfig::TYPE_BEFORE_REMOVING
+ ),
+ array (
+ 'FOS\ElasticaBundle\DependencyInjection\Compiler\TransformerPass'
+ ),
+ );
+
$container = $this
->getMock('Symfony\Component\DependencyInjection\ContainerBuilder');
$container
- ->expects($this->atLeastOnce())
+ ->expects($this->at(0))
->method('addCompilerPass')
- ->with($this->isInstanceOf('Symfony\\Component\\DependencyInjection\\Compiler\\CompilerPassInterface'));
+ ->with($this->isInstanceOf($passes[0][0]), $passes[0][1]);
+
+ $container
+ ->expects($this->at(1))
+ ->method('addCompilerPass')
+ ->with($this->isInstanceOf($passes[1][0]));
$bundle = new FOSElasticaBundle();
+
$bundle->build($container);
}
}
diff --git a/Tests/Functional/ClientTest.php b/Tests/Functional/ClientTest.php
deleted file mode 100644
index 8a6357a..0000000
--- a/Tests/Functional/ClientTest.php
+++ /dev/null
@@ -1,48 +0,0 @@
-
- *
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
- */
-
-namespace FOS\ElasticaBundle\Tests\Functional;
-
-use Symfony\Bundle\FrameworkBundle\Client;
-
-/**
- * @group functional
- */
-class ClientTest extends WebTestCase
-{
- public function testContainerSource()
- {
- $client = $this->createClient(array('test_case' => 'Basic'));
-
- $es = $client->getContainer()->get('fos_elastica.client.default');
- $this->assertInstanceOf('Elastica\\Connection\\Strategy\\RoundRobin', $es->getConnectionStrategy());
-
- $es = $client->getContainer()->get('fos_elastica.client.second_server');
- $this->assertInstanceOf('Elastica\\Connection\\Strategy\\RoundRobin', $es->getConnectionStrategy());
-
- $es = $client->getContainer()->get('fos_elastica.client.third');
- $this->assertInstanceOf('Elastica\\Connection\\Strategy\\Simple', $es->getConnectionStrategy());
- }
-
- protected function setUp()
- {
- parent::setUp();
-
- $this->deleteTmpDir('Basic');
- }
-
- protected function tearDown()
- {
- parent::tearDown();
-
- $this->deleteTmpDir('Basic');
- }
-}
diff --git a/Tests/Functional/ConfigurationManagerTest.php b/Tests/Functional/ConfigurationManagerTest.php
deleted file mode 100644
index a6028b7..0000000
--- a/Tests/Functional/ConfigurationManagerTest.php
+++ /dev/null
@@ -1,59 +0,0 @@
-
- *
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
- */
-
-namespace FOS\ElasticaBundle\Tests\Functional;
-
-use Symfony\Bundle\FrameworkBundle\Client;
-
-/**
- * @group functional
- */
-class ConfigurationManagerTest extends WebTestCase
-{
- public function testContainerSource()
- {
- $client = $this->createClient(array('test_case' => 'Basic'));
- $manager = $this->getManager($client);
-
- $index = $manager->getIndexConfiguration('index');
-
- $this->assertEquals('index', $index->getName());
- $this->assertGreaterThanOrEqual(2, count($index->getTypes()));
- $this->assertInstanceOf('FOS\\ElasticaBundle\\Configuration\\TypeConfig', $index->getType('type'));
- $this->assertInstanceOf('FOS\\ElasticaBundle\\Configuration\\TypeConfig', $index->getType('parent'));
- }
-
- protected function setUp()
- {
- parent::setUp();
-
- $this->deleteTmpDir('Basic');
- }
-
- protected function tearDown()
- {
- parent::tearDown();
-
- $this->deleteTmpDir('Basic');
- }
-
- /**
- * @param Client $client
- *
- * @return \FOS\ElasticaBundle\Configuration\ConfigManager
- */
- private function getManager(Client $client)
- {
- $manager = $client->getContainer()->get('fos_elastica.config_manager');
-
- return $manager;
- }
-}
diff --git a/Tests/Functional/IndexableCallbackTest.php b/Tests/Functional/IndexableCallbackTest.php
deleted file mode 100644
index 3f84286..0000000
--- a/Tests/Functional/IndexableCallbackTest.php
+++ /dev/null
@@ -1,52 +0,0 @@
-
- *
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
- */
-
-namespace FOS\ElasticaBundle\Tests\Functional;
-
-/**
- * @group functional
- */
-class IndexableCallbackTest extends WebTestCase
-{
- /**
- * 2 reasons for this test:.
- *
- * 1) To test that the configuration rename from is_indexable_callback under the listener
- * key is respected, and
- * 2) To test the Extension's set up of the Indexable service.
- */
- public function testIndexableCallback()
- {
- $client = $this->createClient(array('test_case' => 'ORM'));
-
- /** @var \FOS\ElasticaBundle\Provider\Indexable $in */
- $in = $client->getContainer()->get('fos_elastica.indexable');
-
- $this->assertTrue($in->isObjectIndexable('index', 'type', new TypeObj()));
- $this->assertTrue($in->isObjectIndexable('index', 'type2', new TypeObj()));
- $this->assertFalse($in->isObjectIndexable('index', 'type3', new TypeObj()));
- $this->assertFalse($in->isObjectIndexable('index', 'type4', new TypeObj()));
- }
-
- protected function setUp()
- {
- parent::setUp();
-
- $this->deleteTmpDir('ORM');
- }
-
- protected function tearDown()
- {
- parent::tearDown();
-
- $this->deleteTmpDir('ORM');
- }
-}
diff --git a/Tests/Functional/MappingToElasticaTest.php b/Tests/Functional/MappingToElasticaTest.php
deleted file mode 100644
index 6f93b7e..0000000
--- a/Tests/Functional/MappingToElasticaTest.php
+++ /dev/null
@@ -1,140 +0,0 @@
-
- *
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
- */
-
-namespace FOS\ElasticaBundle\Tests\Functional;
-
-use Symfony\Bundle\FrameworkBundle\Client;
-
-/**
- * @group functional
- */
-class MappingToElasticaTest extends WebTestCase
-{
- public function testResetIndexAddsMappings()
- {
- $client = $this->createClient(array('test_case' => 'Basic'));
- $resetter = $this->getResetter($client);
- $resetter->resetIndex('index');
-
- $type = $this->getType($client);
- $mapping = $type->getMapping();
-
- $this->assertNotEmpty($mapping, 'Mapping was populated');
- $this->assertArrayHasKey('store', $mapping['type']['properties']['field1']);
- $this->assertTrue($mapping['type']['properties']['field1']['store']);
- $this->assertArrayNotHasKey('store', $mapping['type']['properties']['field2']);
-
- $type = $this->getType($client, 'type');
- $mapping = $type->getMapping();
- $this->assertEquals('parent', $mapping['type']['_parent']['type']);
-
- $parent = $this->getType($client, 'parent');
- $mapping = $parent->getMapping();
-
- $this->assertEquals('my_analyzer', $mapping['parent']['index_analyzer']);
- $this->assertEquals('whitespace', $mapping['parent']['search_analyzer']);
- }
-
- public function testResetType()
- {
- $client = $this->createClient(array('test_case' => 'Basic'));
- $resetter = $this->getResetter($client);
- $resetter->resetIndexType('index', 'type');
-
- $type = $this->getType($client);
- $mapping = $type->getMapping();
-
- $this->assertNotEmpty($mapping, 'Mapping was populated');
- $this->assertFalse($mapping['type']['date_detection']);
- $this->assertTrue($mapping['type']['numeric_detection']);
- $this->assertEquals(array('yyyy-MM-dd'), $mapping['type']['dynamic_date_formats']);
- $this->assertArrayHasKey('store', $mapping['type']['properties']['field1']);
- $this->assertTrue($mapping['type']['properties']['field1']['store']);
- $this->assertArrayNotHasKey('store', $mapping['type']['properties']['field2']);
- }
-
- public function testORMResetIndexAddsMappings()
- {
- $client = $this->createClient(array('test_case' => 'ORM'));
- $resetter = $this->getResetter($client);
- $resetter->resetIndex('index');
-
- $type = $this->getType($client);
- $mapping = $type->getMapping();
-
- $this->assertNotEmpty($mapping, 'Mapping was populated');
- }
-
- public function testORMResetType()
- {
- $client = $this->createClient(array('test_case' => 'ORM'));
- $resetter = $this->getResetter($client);
- $resetter->resetIndexType('index', 'type');
-
- $type = $this->getType($client);
- $mapping = $type->getMapping();
-
- $this->assertNotEmpty($mapping, 'Mapping was populated');
- }
-
- public function testMappingIteratorToArrayField()
- {
- $client = $this->createClient(array('test_case' => 'ORM'));
- $persister = $client->getContainer()->get('fos_elastica.object_persister.index.type');
-
- $object = new TypeObj();
- $object->id = 1;
- $object->coll = new \ArrayIterator(array('foo', 'bar'));
- $persister->insertOne($object);
-
- $object->coll = new \ArrayIterator(array('foo', 'bar', 'bazz'));
- $object->coll->offsetUnset(1);
-
- $persister->replaceOne($object);
- }
-
- /**
- * @param Client $client
- *
- * @return \FOS\ElasticaBundle\Resetter $resetter
- */
- private function getResetter(Client $client)
- {
- return $client->getContainer()->get('fos_elastica.resetter');
- }
-
- /**
- * @param Client $client
- * @param string $type
- *
- * @return \Elastica\Type
- */
- private function getType(Client $client, $type = 'type')
- {
- return $client->getContainer()->get('fos_elastica.index.index.'.$type);
- }
-
- protected function setUp()
- {
- parent::setUp();
-
- $this->deleteTmpDir('Basic');
- $this->deleteTmpDir('ORM');
- }
-
- protected function tearDown()
- {
- parent::tearDown();
-
- $this->deleteTmpDir('Basic');
- $this->deleteTmpDir('ORM');
- }
-}
diff --git a/Tests/Functional/PropertyPathTest.php b/Tests/Functional/PropertyPathTest.php
deleted file mode 100644
index 860cb86..0000000
--- a/Tests/Functional/PropertyPathTest.php
+++ /dev/null
@@ -1,54 +0,0 @@
-
- *
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
- */
-
-namespace FOS\ElasticaBundle\Tests\Functional;
-
-use Elastica\Query\Match;
-
-/**
- * @group functional
- */
-class PropertyPathTest extends WebTestCase
-{
- public function testContainerSource()
- {
- $client = $this->createClient(array('test_case' => 'ORM'));
- /** @var \FOS\ElasticaBundle\Persister\ObjectPersister $persister */
- $persister = $client->getContainer()->get('fos_elastica.object_persister.index.property_paths_type');
- $obj = new TypeObj();
- $obj->coll = 'Hello';
- $persister->insertOne($obj);
-
- /** @var \Elastica\Index $elClient */
- $index = $client->getContainer()->get('fos_elastica.index.index');
- $index->flush(true);
-
- $query = new Match();
- $query->setField('something', 'Hello');
- $search = $index->createSearch($query);
-
- $this->assertEquals(1, $search->count());
- }
-
- protected function setUp()
- {
- parent::setUp();
-
- $this->deleteTmpDir('Basic');
- }
-
- protected function tearDown()
- {
- parent::tearDown();
-
- $this->deleteTmpDir('Basic');
- }
-}
diff --git a/Tests/Functional/SerializerTest.php b/Tests/Functional/SerializerTest.php
deleted file mode 100644
index 81fbc8f..0000000
--- a/Tests/Functional/SerializerTest.php
+++ /dev/null
@@ -1,55 +0,0 @@
-
- *
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
- */
-
-namespace FOS\ElasticaBundle\Tests\Functional;
-
-/**
- * @group functional
- */
-class SerializerTest extends WebTestCase
-{
- public function testMappingIteratorToArrayField()
- {
- $client = $this->createClient(array('test_case' => 'Serializer'));
- $persister = $client->getContainer()->get('fos_elastica.object_persister.index.type');
-
- $object = new TypeObj();
- $object->id = 1;
- $object->coll = new \ArrayIterator(array('foo', 'bar'));
- $persister->insertOne($object);
-
- $object->coll = new \ArrayIterator(array('foo', 'bar', 'bazz'));
- $object->coll->offsetUnset(1);
-
- $persister->replaceOne($object);
- }
-
- public function testUnmappedType()
- {
- $client = $this->createClient(array('test_case' => 'Serializer'));
- $resetter = $client->getContainer()->get('fos_elastica.resetter');
- $resetter->resetIndex('index');
- }
-
- protected function setUp()
- {
- parent::setUp();
-
- $this->deleteTmpDir('Serializer');
- }
-
- protected function tearDown()
- {
- parent::tearDown();
-
- $this->deleteTmpDir('Serializer');
- }
-}
diff --git a/Tests/Functional/TypeObj.php b/Tests/Functional/TypeObj.php
deleted file mode 100644
index 39e9fe9..0000000
--- a/Tests/Functional/TypeObj.php
+++ /dev/null
@@ -1,35 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace FOS\ElasticaBundle\Tests\Functional;
-
-class TypeObj
-{
- public $id = 5;
- public $coll;
- public $field1;
- public $field2;
-
- public function isIndexable()
- {
- return true;
- }
-
- public function isntIndexable()
- {
- return false;
- }
-
- public function getSerializableColl()
- {
- return iterator_to_array($this->coll, false);
- }
-}
diff --git a/Tests/Functional/WebTestCase.php b/Tests/Functional/WebTestCase.php
deleted file mode 100644
index 38f5489..0000000
--- a/Tests/Functional/WebTestCase.php
+++ /dev/null
@@ -1,40 +0,0 @@
-
- *
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
- */
-
-namespace FOS\ElasticaBundle\Tests\Functional;
-
-use Symfony\Bundle\FrameworkBundle\Tests\Functional\WebTestCase as BaseWebTestCase;
-
-class WebTestCase extends BaseWebTestCase
-{
- protected static function getKernelClass()
- {
- require_once __DIR__.'/app/AppKernel.php';
-
- return 'FOS\ElasticaBundle\Tests\Functional\app\AppKernel';
- }
-
- protected static function createKernel(array $options = array())
- {
- $class = self::getKernelClass();
-
- if (!isset($options['test_case'])) {
- throw new \InvalidArgumentException('The option "test_case" must be set.');
- }
-
- return new $class(
- $options['test_case'],
- isset($options['root_config']) ? $options['root_config'] : 'config.yml',
- isset($options['environment']) ? $options['environment'] : 'foselasticabundle'.strtolower($options['test_case']),
- isset($options['debug']) ? $options['debug'] : true
- );
- }
-}
diff --git a/Tests/Functional/app/AppKernel.php b/Tests/Functional/app/AppKernel.php
deleted file mode 100644
index d75910a..0000000
--- a/Tests/Functional/app/AppKernel.php
+++ /dev/null
@@ -1,118 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace FOS\ElasticaBundle\Tests\Functional\app;
-
-// get the autoload file
-$dir = __DIR__;
-$lastDir = null;
-while ($dir !== $lastDir) {
- $lastDir = $dir;
-
- if (file_exists($dir.'/autoload.php')) {
- require_once $dir.'/autoload.php';
- break;
- }
-
- if (file_exists($dir.'/autoload.php.dist')) {
- require_once $dir.'/autoload.php.dist';
- break;
- }
-
- if (file_exists($dir.'/vendor/autoload.php')) {
- require_once $dir.'/vendor/autoload.php';
- break;
- }
-
- $dir = dirname($dir);
-}
-
-use Symfony\Component\Config\Loader\LoaderInterface;
-use Symfony\Component\Filesystem\Filesystem;
-use Symfony\Component\HttpKernel\Kernel;
-
-/**
- * App Test Kernel for functional tests.
- *
- * @author Johannes M. Schmitt
- */
-class AppKernel extends Kernel
-{
- private $testCase;
- private $rootConfig;
-
- public function __construct($testCase, $rootConfig, $environment, $debug)
- {
- if (!is_dir(__DIR__.'/'.$testCase)) {
- throw new \InvalidArgumentException(sprintf('The test case "%s" does not exist.', $testCase));
- }
- $this->testCase = $testCase;
-
- $fs = new Filesystem();
- if (!$fs->isAbsolutePath($rootConfig) && !file_exists($rootConfig = __DIR__.'/'.$testCase.'/'.$rootConfig)) {
- throw new \InvalidArgumentException(sprintf('The root config "%s" does not exist.', $rootConfig));
- }
- $this->rootConfig = $rootConfig;
-
- parent::__construct($environment, $debug);
- }
-
- public function registerBundles()
- {
- if (!file_exists($filename = $this->getRootDir().'/'.$this->testCase.'/bundles.php')) {
- throw new \RuntimeException(sprintf('The bundles file "%s" does not exist.', $filename));
- }
-
- return include $filename;
- }
-
- public function init()
- {
- }
-
- public function getRootDir()
- {
- return __DIR__;
- }
-
- public function getCacheDir()
- {
- return sys_get_temp_dir().'/'.Kernel::VERSION.'/'.$this->testCase.'/cache/'.$this->environment;
- }
-
- public function getLogDir()
- {
- return sys_get_temp_dir().'/'.Kernel::VERSION.'/'.$this->testCase.'/logs';
- }
-
- public function registerContainerConfiguration(LoaderInterface $loader)
- {
- $loader->load($this->rootConfig);
- }
-
- public function serialize()
- {
- return serialize(array($this->testCase, $this->rootConfig, $this->getEnvironment(), $this->isDebug()));
- }
-
- public function unserialize($str)
- {
- call_user_func_array(array($this, '__construct'), unserialize($str));
- }
-
- protected function getKernelParameters()
- {
- $parameters = parent::getKernelParameters();
- $parameters['kernel.test_case'] = $this->testCase;
-
- return $parameters;
- }
-}
diff --git a/Tests/Functional/app/Basic/bundles.php b/Tests/Functional/app/Basic/bundles.php
deleted file mode 100644
index 7bcaae8..0000000
--- a/Tests/Functional/app/Basic/bundles.php
+++ /dev/null
@@ -1,13 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace FOS\ElasticaBundle\Tests\Functional\app\ORM;
-
-class IndexableService
-{
- public function isIndexable()
- {
- return true;
- }
-
- public static function isntIndexable()
- {
- return false;
- }
-}
diff --git a/Tests/Functional/app/ORM/bundles.php b/Tests/Functional/app/ORM/bundles.php
deleted file mode 100644
index 25db3fe..0000000
--- a/Tests/Functional/app/ORM/bundles.php
+++ /dev/null
@@ -1,13 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace FOS\ElasticaBundle\Tests\Index;
-
-use Elastica\Exception\ResponseException;
-use Elastica\Request;
-use Elastica\Response;
-use FOS\ElasticaBundle\Configuration\IndexConfig;
-use FOS\ElasticaBundle\Index\AliasProcessor;
-
-class AliasProcessorTest extends \PHPUnit_Framework_TestCase
-{
- /**
- * @var AliasProcessor
- */
- private $processor;
-
- /**
- * @dataProvider getSetRootNameData
- * @param string $name
- * @param array $configArray
- * @param string $resultStartsWith
- */
- public function testSetRootName($name, $configArray, $resultStartsWith)
- {
- $indexConfig = new IndexConfig($name, array(), $configArray);
- $index = $this->getMockBuilder('FOS\\ElasticaBundle\\Elastica\\Index')
- ->disableOriginalConstructor()
- ->getMock();
- $index->expects($this->once())
- ->method('overrideName')
- ->with($this->stringStartsWith($resultStartsWith));
-
- $this->processor->setRootName($indexConfig, $index);
- }
-
- public function testSwitchAliasNoAliasSet()
- {
- $indexConfig = new IndexConfig('name', array(), array());
- list($index, $client) = $this->getMockedIndex('unique_name');
-
- $client->expects($this->at(0))
- ->method('request')
- ->with('_aliases', 'GET')
- ->willReturn(new Response(array()));
- $client->expects($this->at(1))
- ->method('request')
- ->with('_aliases', 'POST', array('actions' => array(
- array('add' => array('index' => 'unique_name', 'alias' => 'name'))
- )));
-
- $this->processor->switchIndexAlias($indexConfig, $index, false);
- }
-
- public function testSwitchAliasExistingAliasSet()
- {
- $indexConfig = new IndexConfig('name', array(), array());
- list($index, $client) = $this->getMockedIndex('unique_name');
-
- $client->expects($this->at(0))
- ->method('request')
- ->with('_aliases', 'GET')
- ->willReturn(new Response(array(
- 'old_unique_name' => array('aliases' => array('name'))
- )));
- $client->expects($this->at(1))
- ->method('request')
- ->with('_aliases', 'POST', array('actions' => array(
- array('remove' => array('index' => 'old_unique_name', 'alias' => 'name')),
- array('add' => array('index' => 'unique_name', 'alias' => 'name'))
- )));
-
- $this->processor->switchIndexAlias($indexConfig, $index, false);
- }
-
- /**
- * @expectedException \RuntimeException
- */
- public function testSwitchAliasThrowsWhenMoreThanOneExists()
- {
- $indexConfig = new IndexConfig('name', array(), array());
- list($index, $client) = $this->getMockedIndex('unique_name');
-
- $client->expects($this->at(0))
- ->method('request')
- ->with('_aliases', 'GET')
- ->willReturn(new Response(array(
- 'old_unique_name' => array('aliases' => array('name')),
- 'another_old_unique_name' => array('aliases' => array('name'))
- )));
-
- $this->processor->switchIndexAlias($indexConfig, $index, false);
- }
-
- /**
- * @expectedException \FOS\ElasticaBundle\Exception\AliasIsIndexException
- */
- public function testSwitchAliasThrowsWhenAliasIsAnIndex()
- {
- $indexConfig = new IndexConfig('name', array(), array());
- list($index, $client) = $this->getMockedIndex('unique_name');
-
- $client->expects($this->at(0))
- ->method('request')
- ->with('_aliases', 'GET')
- ->willReturn(new Response(array(
- 'name' => array(),
- )));
-
- $this->processor->switchIndexAlias($indexConfig, $index, false);
- }
-
- public function testSwitchAliasDeletesIndexCollisionIfForced()
- {
- $indexConfig = new IndexConfig('name', array(), array());
- list($index, $client) = $this->getMockedIndex('unique_name');
-
- $client->expects($this->at(0))
- ->method('request')
- ->with('_aliases', 'GET')
- ->willReturn(new Response(array(
- 'name' => array(),
- )));
- $client->expects($this->at(1))
- ->method('request')
- ->with('name', 'DELETE');
-
- $this->processor->switchIndexAlias($indexConfig, $index, true);
- }
-
- public function testSwitchAliasDeletesOldIndex()
- {
- $indexConfig = new IndexConfig('name', array(), array());
- list($index, $client) = $this->getMockedIndex('unique_name');
-
- $client->expects($this->at(0))
- ->method('request')
- ->with('_aliases', 'GET')
- ->willReturn(new Response(array(
- 'old_unique_name' => array('aliases' => array('name')),
- )));
- $client->expects($this->at(1))
- ->method('request')
- ->with('_aliases', 'POST', array('actions' => array(
- array('remove' => array('index' => 'old_unique_name', 'alias' => 'name')),
- array('add' => array('index' => 'unique_name', 'alias' => 'name'))
- )));
- $client->expects($this->at(2))
- ->method('request')
- ->with('old_unique_name', 'DELETE');
-
- $this->processor->switchIndexAlias($indexConfig, $index, true);
- }
-
- public function testSwitchAliasCleansUpOnRenameFailure()
- {
- $indexConfig = new IndexConfig('name', array(), array());
- list($index, $client) = $this->getMockedIndex('unique_name');
-
- $client->expects($this->at(0))
- ->method('request')
- ->with('_aliases', 'GET')
- ->willReturn(new Response(array(
- 'old_unique_name' => array('aliases' => array('name')),
- )));
- $client->expects($this->at(1))
- ->method('request')
- ->with('_aliases', 'POST', array('actions' => array(
- array('remove' => array('index' => 'old_unique_name', 'alias' => 'name')),
- array('add' => array('index' => 'unique_name', 'alias' => 'name'))
- )))
- ->will($this->throwException(new ResponseException(new Request(''), new Response(''))));
- $client->expects($this->at(2))
- ->method('request')
- ->with('unique_name', 'DELETE');
- // Not an annotation: we do not want a RuntimeException until now.
- $this->setExpectedException('RuntimeException');
-
- $this->processor->switchIndexAlias($indexConfig, $index, true);
- }
-
- public function getSetRootNameData()
- {
- return array(
- array('name', array(), 'name_'),
- array('name', array('elasticSearchName' => 'notname'), 'notname_')
- );
- }
-
- protected function setUp()
- {
- $this->processor = new AliasProcessor();
- }
-
- private function getMockedIndex($name)
- {
- $index = $this->getMockBuilder('FOS\\ElasticaBundle\\Elastica\\Index')
- ->disableOriginalConstructor()
- ->getMock();
-
- $client = $this->getMockBuilder('Elastica\\Client')
- ->disableOriginalConstructor()
- ->getMock();
- $index->expects($this->any())
- ->method('getClient')
- ->willReturn($client);
-
- $index->expects($this->any())
- ->method('getName')
- ->willReturn($name);
-
- return array($index, $client);
- }
-}
diff --git a/Tests/Index/IndexManagerTest.php b/Tests/Index/IndexManagerTest.php
index 78a3d28..624f64e 100644
--- a/Tests/Index/IndexManagerTest.php
+++ b/Tests/Index/IndexManagerTest.php
@@ -6,40 +6,40 @@ use FOS\ElasticaBundle\Index\IndexManager;
class IndexManagerTest extends \PHPUnit_Framework_TestCase
{
- private $indexes = array();
-
- /**
- * @var IndexManager
- */
+ private $defaultIndexName;
+ private $indexesByName;
+ /** @var IndexManager */
private $indexManager;
public function setUp()
{
- foreach (array('index1', 'index2', 'index3') as $indexName) {
- $index = $this->getMockBuilder('FOS\\ElasticaBundle\\Elastica\\Index')
- ->disableOriginalConstructor()
- ->getMock();
+ $this->defaultIndexName = 'index2';
+ $this->indexesByName = array(
+ 'index1' => 'test1',
+ 'index2' => 'test2',
+ );
- $index->expects($this->any())
- ->method('getName')
- ->will($this->returnValue($indexName));
+ /** @var $defaultIndex \PHPUnit_Framework_MockObject_MockObject|\Elastica\Index */
+ $defaultIndex = $this->getMockBuilder('Elastica\Index')
+ ->disableOriginalConstructor()
+ ->getMock();
- $this->indexes[$indexName] = $index;
- }
+ $defaultIndex->expects($this->any())
+ ->method('getName')
+ ->will($this->returnValue($this->defaultIndexName));
- $this->indexManager = new IndexManager($this->indexes, $this->indexes['index2']);
+ $this->indexManager = new IndexManager($this->indexesByName, $defaultIndex);
}
public function testGetAllIndexes()
{
- $this->assertEquals($this->indexes, $this->indexManager->getAllIndexes());
+ $this->assertEquals($this->indexesByName, $this->indexManager->getAllIndexes());
}
public function testGetIndex()
{
- $this->assertEquals($this->indexes['index1'], $this->indexManager->getIndex('index1'));
- $this->assertEquals($this->indexes['index2'], $this->indexManager->getIndex('index2'));
- $this->assertEquals($this->indexes['index3'], $this->indexManager->getIndex('index3'));
+ $this->assertEquals($this->indexesByName['index1'], $this->indexManager->getIndex('index1'));
+ $this->assertEquals($this->indexesByName['index2'], $this->indexManager->getIndex('index2'));
}
/**
@@ -47,12 +47,12 @@ class IndexManagerTest extends \PHPUnit_Framework_TestCase
*/
public function testGetIndexShouldThrowExceptionForInvalidName()
{
- $this->indexManager->getIndex('index4');
+ $this->indexManager->getIndex('index3');
}
public function testGetDefaultIndex()
{
- $this->assertEquals('index2', $this->indexManager->getIndex()->getName());
- $this->assertEquals('index2', $this->indexManager->getDefaultIndex()->getName());
+ $this->assertEquals('test2', $this->indexManager->getIndex());
+ $this->assertEquals('test2', $this->indexManager->getDefaultIndex());
}
}
diff --git a/Tests/Index/ResetterTest.php b/Tests/Index/ResetterTest.php
index 9b4cd05..7b1c2fa 100644
--- a/Tests/Index/ResetterTest.php
+++ b/Tests/Index/ResetterTest.php
@@ -5,270 +5,199 @@ namespace FOS\ElasticaBundle\Tests\Index;
use Elastica\Exception\ResponseException;
use Elastica\Request;
use Elastica\Response;
-use Elastica\Type;
use Elastica\Type\Mapping;
-use FOS\ElasticaBundle\Configuration\IndexConfig;
-use FOS\ElasticaBundle\Configuration\TypeConfig;
-use FOS\ElasticaBundle\Elastica\Index;
-use FOS\ElasticaBundle\Event\IndexResetEvent;
-use FOS\ElasticaBundle\Event\TypeResetEvent;
-use FOS\ElasticaBundle\Index\AliasProcessor;
use FOS\ElasticaBundle\Index\Resetter;
class ResetterTest extends \PHPUnit_Framework_TestCase
{
- /**
- * @var Resetter
- */
- private $resetter;
+ private $indexConfigsByName;
- private $aliasProcessor;
- private $configManager;
- private $dispatcher;
- private $elasticaClient;
- private $indexManager;
- private $mappingBuilder;
+ public function setUp()
+ {
+ $this->indexConfigsByName = array(
+ 'foo' => array(
+ 'index' => $this->getMockElasticaIndex(),
+ 'config' => array(
+ 'mappings' => array(
+ 'a' => array(
+ 'dynamic_templates' => array(),
+ 'properties' => array(),
+ ),
+ 'b' => array('properties' => array()),
+ ),
+ ),
+ ),
+ 'bar' => array(
+ 'index' => $this->getMockElasticaIndex(),
+ 'config' => array(
+ 'mappings' => array(
+ 'a' => array('properties' => array()),
+ 'b' => array('properties' => array()),
+ ),
+ ),
+ ),
+ 'parent' => array(
+ 'index' => $this->getMockElasticaIndex(),
+ 'config' => array(
+ 'mappings' => array(
+ 'a' => array(
+ 'properties' => array(
+ 'field_2' => array()
+ ),
+ '_parent' => array(
+ 'type' => 'b',
+ 'property' => 'b',
+ 'identifier' => 'id'
+ ),
+ ),
+ 'b' => array('properties' => array()),
+ ),
+ ),
+ ),
+ );
+ }
public function testResetAllIndexes()
{
- $indexName = 'index1';
- $indexConfig = new IndexConfig($indexName, array(), array());
- $this->mockIndex($indexName, $indexConfig);
+ $this->indexConfigsByName['foo']['index']->expects($this->once())
+ ->method('create')
+ ->with($this->indexConfigsByName['foo']['config'], true);
- $this->configManager->expects($this->once())
- ->method('getIndexNames')
- ->will($this->returnValue(array($indexName)));
+ $this->indexConfigsByName['bar']['index']->expects($this->once())
+ ->method('create')
+ ->with($this->indexConfigsByName['bar']['config'], true);
- $this->dispatcherExpects(array(
- array(IndexResetEvent::PRE_INDEX_RESET, $this->isInstanceOf('FOS\\ElasticaBundle\\Event\\IndexResetEvent')),
- array(IndexResetEvent::POST_INDEX_RESET, $this->isInstanceOf('FOS\\ElasticaBundle\\Event\\IndexResetEvent'))
- ));
-
- $this->elasticaClient->expects($this->exactly(2))
- ->method('request')
- ->withConsecutive(
- array('index1/', 'DELETE'),
- array('index1/', 'PUT', array(), array())
- );
-
- $this->resetter->resetAllIndexes();
+ $resetter = new Resetter($this->indexConfigsByName);
+ $resetter->resetAllIndexes();
}
public function testResetIndex()
{
- $indexConfig = new IndexConfig('index1', array(), array());
- $this->mockIndex('index1', $indexConfig);
+ $this->indexConfigsByName['foo']['index']->expects($this->once())
+ ->method('create')
+ ->with($this->indexConfigsByName['foo']['config'], true);
- $this->dispatcherExpects(array(
- array(IndexResetEvent::PRE_INDEX_RESET, $this->isInstanceOf('FOS\\ElasticaBundle\\Event\\IndexResetEvent')),
- array(IndexResetEvent::POST_INDEX_RESET, $this->isInstanceOf('FOS\\ElasticaBundle\\Event\\IndexResetEvent'))
- ));
+ $this->indexConfigsByName['bar']['index']->expects($this->never())
+ ->method('create');
- $this->elasticaClient->expects($this->exactly(2))
- ->method('request')
- ->withConsecutive(
- array('index1/', 'DELETE'),
- array('index1/', 'PUT', array(), array())
- );
-
- $this->resetter->resetIndex('index1');
- }
-
- public function testResetIndexWithDifferentName()
- {
- $indexConfig = new IndexConfig('index1', array(), array(
- 'elasticSearchName' => 'notIndex1'
- ));
- $this->mockIndex('index1', $indexConfig);
- $this->dispatcherExpects(array(
- array(IndexResetEvent::PRE_INDEX_RESET, $this->isInstanceOf('FOS\\ElasticaBundle\\Event\\IndexResetEvent')),
- array(IndexResetEvent::POST_INDEX_RESET, $this->isInstanceOf('FOS\\ElasticaBundle\\Event\\IndexResetEvent'))
- ));
-
- $this->elasticaClient->expects($this->exactly(2))
- ->method('request')
- ->withConsecutive(
- array('index1/', 'DELETE'),
- array('index1/', 'PUT', array(), array())
- );
-
- $this->resetter->resetIndex('index1');
- }
-
- public function testResetIndexWithDifferentNameAndAlias()
- {
- $indexConfig = new IndexConfig('index1', array(), array(
- 'elasticSearchName' => 'notIndex1',
- 'useAlias' => true
- ));
- $index = $this->mockIndex('index1', $indexConfig);
- $this->dispatcherExpects(array(
- array(IndexResetEvent::PRE_INDEX_RESET, $this->isInstanceOf('FOS\\ElasticaBundle\\Event\\IndexResetEvent')),
- array(IndexResetEvent::POST_INDEX_RESET, $this->isInstanceOf('FOS\\ElasticaBundle\\Event\\IndexResetEvent'))
- ));
-
- $this->aliasProcessor->expects($this->once())
- ->method('switchIndexAlias')
- ->with($indexConfig, $index, false);
-
- $this->elasticaClient->expects($this->exactly(2))
- ->method('request')
- ->withConsecutive(
- array('index1/', 'DELETE'),
- array('index1/', 'PUT', array(), array())
- );
-
- $this->resetter->resetIndex('index1');
+ $resetter = new Resetter($this->indexConfigsByName);
+ $resetter->resetIndex('foo');
}
/**
* @expectedException \InvalidArgumentException
*/
- public function testFailureWhenMissingIndexDoesntDispatch()
+ public function testResetIndexShouldThrowExceptionForInvalidIndex()
{
- $this->configManager->expects($this->once())
- ->method('getIndexConfiguration')
- ->with('nonExistant')
- ->will($this->throwException(new \InvalidArgumentException));
-
- $this->indexManager->expects($this->never())
- ->method('getIndex');
-
- $this->resetter->resetIndex('nonExistant');
+ $resetter = new Resetter($this->indexConfigsByName);
+ $resetter->resetIndex('baz');
}
- public function testResetType()
+ public function testResetIndexType()
{
- $typeConfig = new TypeConfig('type', array(), array());
- $this->mockType('type', 'index', $typeConfig);
+ $type = $this->getMockElasticaType();
- $this->dispatcherExpects(array(
- array(TypeResetEvent::PRE_TYPE_RESET, $this->isInstanceOf('FOS\\ElasticaBundle\\Event\\TypeResetEvent')),
- array(TypeResetEvent::POST_TYPE_RESET, $this->isInstanceOf('FOS\\ElasticaBundle\\Event\\TypeResetEvent'))
- ));
+ $this->indexConfigsByName['foo']['index']->expects($this->once())
+ ->method('getType')
+ ->with('a')
+ ->will($this->returnValue($type));
- $this->elasticaClient->expects($this->exactly(2))
- ->method('request')
- ->withConsecutive(
- array('index/type/', 'DELETE'),
- array('index/type/_mapping', 'PUT', array('type' => array()), array())
- );
+ $type->expects($this->once())
+ ->method('delete');
- $this->resetter->resetIndexType('index', 'type');
+ $mapping = Mapping::create($this->indexConfigsByName['foo']['config']['mappings']['a']['properties']);
+ $mapping->setParam('dynamic_templates', $this->indexConfigsByName['foo']['config']['mappings']['a']['dynamic_templates']);
+ $type->expects($this->once())
+ ->method('setMapping')
+ ->with($mapping);
+
+ $resetter = new Resetter($this->indexConfigsByName);
+ $resetter->resetIndexType('foo', 'a');
}
/**
* @expectedException \InvalidArgumentException
*/
- public function testNonExistantResetType()
+ public function testResetIndexTypeShouldThrowExceptionForInvalidIndex()
{
- $this->configManager->expects($this->once())
- ->method('getTypeConfiguration')
- ->with('index', 'nonExistant')
- ->will($this->throwException(new \InvalidArgumentException));
-
- $this->indexManager->expects($this->never())
- ->method('getIndex');
-
- $this->resetter->resetIndexType('index', 'nonExistant');
+ $resetter = new Resetter($this->indexConfigsByName);
+ $resetter->resetIndexType('baz', 'a');
}
- public function testPostPopulateWithoutAlias()
+ /**
+ * @expectedException \InvalidArgumentException
+ */
+ public function testResetIndexTypeShouldThrowExceptionForInvalidType()
{
- $this->mockIndex('index', new IndexConfig('index', array(), array()));
-
- $this->indexManager->expects($this->never())
- ->method('getIndex');
- $this->aliasProcessor->expects($this->never())
- ->method('switchIndexAlias');
-
- $this->resetter->postPopulate('index');
+ $resetter = new Resetter($this->indexConfigsByName);
+ $resetter->resetIndexType('foo', 'c');
}
- public function testPostPopulate()
+ public function testResetIndexTypeIgnoreTypeMissingException()
{
- $indexConfig = new IndexConfig('index', array(), array( 'useAlias' => true));
- $index = $this->mockIndex('index', $indexConfig);
+ $type = $this->getMockElasticaType();
- $this->aliasProcessor->expects($this->once())
- ->method('switchIndexAlias')
- ->with($indexConfig, $index);
+ $this->indexConfigsByName['foo']['index']->expects($this->once())
+ ->method('getType')
+ ->with('a')
+ ->will($this->returnValue($type));
- $this->resetter->postPopulate('index');
+ $type->expects($this->once())
+ ->method('delete')
+ ->will($this->throwException(new ResponseException(
+ new Request(''),
+ new Response(array('error' => 'TypeMissingException[[de_20131022] type[bla] missing]', 'status' => 404)))
+ ));
+
+ $mapping = Mapping::create($this->indexConfigsByName['foo']['config']['mappings']['a']['properties']);
+ $mapping->setParam('dynamic_templates', $this->indexConfigsByName['foo']['config']['mappings']['a']['dynamic_templates']);
+ $type->expects($this->once())
+ ->method('setMapping')
+ ->with($mapping);
+
+ $resetter = new Resetter($this->indexConfigsByName);
+ $resetter->resetIndexType('foo', 'a');
}
- private function dispatcherExpects(array $events)
+ public function testIndexMappingForParent()
{
- $expectation = $this->dispatcher->expects($this->exactly(count($events)))
- ->method('dispatch');
+ $type = $this->getMockElasticaType();
- call_user_func_array(array($expectation, 'withConsecutive'), $events);
+ $this->indexConfigsByName['parent']['index']->expects($this->once())
+ ->method('getType')
+ ->with('a')
+ ->will($this->returnValue($type));
+
+ $type->expects($this->once())
+ ->method('delete');
+
+ $mapping = Mapping::create($this->indexConfigsByName['parent']['config']['mappings']['a']['properties']);
+ $mapping->setParam('_parent', array('type' => 'b'));
+ $type->expects($this->once())
+ ->method('setMapping')
+ ->with($mapping);
+
+ $resetter = new Resetter($this->indexConfigsByName);
+ $resetter->resetIndexType('parent', 'a');
}
- private function mockIndex($indexName, IndexConfig $config, $mapping = array())
+ /**
+ * @return \Elastica\Index
+ */
+ private function getMockElasticaIndex()
{
- $this->configManager->expects($this->atLeast(1))
- ->method('getIndexConfiguration')
- ->with($indexName)
- ->will($this->returnValue($config));
- $index = new Index($this->elasticaClient, $indexName);
- $this->indexManager->expects($this->any())
- ->method('getIndex')
- ->with($indexName)
- ->willReturn($index);
- $this->mappingBuilder->expects($this->any())
- ->method('buildIndexMapping')
- ->with($config)
- ->willReturn($mapping);
-
- return $index;
- }
-
- private function mockType($typeName, $indexName, TypeConfig $config, $mapping = array())
- {
- $this->configManager->expects($this->atLeast(1))
- ->method('getTypeConfiguration')
- ->with($indexName, $typeName)
- ->will($this->returnValue($config));
- $index = new Index($this->elasticaClient, $indexName);
- $this->indexManager->expects($this->once())
- ->method('getIndex')
- ->with($indexName)
- ->willReturn($index);
- $this->mappingBuilder->expects($this->once())
- ->method('buildTypeMapping')
- ->with($config)
- ->willReturn($mapping);
-
- return $index;
- }
-
- protected function setUp()
- {
- $this->aliasProcessor = $this->getMockBuilder('FOS\\ElasticaBundle\\Index\\AliasProcessor')
- ->disableOriginalConstructor()
- ->getMock();
- $this->configManager = $this->getMockBuilder('FOS\\ElasticaBundle\\Configuration\\ConfigManager')
- ->disableOriginalConstructor()
- ->getMock();
- $this->dispatcher = $this->getMockBuilder('Symfony\\Component\\EventDispatcher\\EventDispatcherInterface')
- ->getMock();
- $this->elasticaClient = $this->getMockBuilder('Elastica\\Client')
- ->disableOriginalConstructor()
- ->getMock();
- $this->indexManager = $this->getMockBuilder('FOS\\ElasticaBundle\\Index\\IndexManager')
- ->disableOriginalConstructor()
- ->getMock();
- $this->mappingBuilder = $this->getMockBuilder('FOS\\ElasticaBundle\\Index\\MappingBuilder')
+ return $this->getMockBuilder('Elastica\Index')
->disableOriginalConstructor()
->getMock();
+ }
- $this->resetter = new Resetter(
- $this->configManager,
- $this->indexManager,
- $this->aliasProcessor,
- $this->mappingBuilder,
- $this->dispatcher
- );
+ /**
+ * @return \Elastica\Type
+ */
+ private function getMockElasticaType()
+ {
+ return $this->getMockBuilder('Elastica\Type')
+ ->disableOriginalConstructor()
+ ->getMock();
}
}
diff --git a/Tests/Integration/MappingTest.php b/Tests/Integration/MappingTest.php
deleted file mode 100644
index ae7e409..0000000
--- a/Tests/Integration/MappingTest.php
+++ /dev/null
@@ -1,15 +0,0 @@
-
- *
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
- */
-
-namespace FOS\ElasticaBundle\Tests\Integration;
-
-class MappingTest
-{
-}
diff --git a/Tests/Logger/ElasticaLoggerTest.php b/Tests/Logger/ElasticaLoggerTest.php
index 7d90639..96adf53 100644
--- a/Tests/Logger/ElasticaLoggerTest.php
+++ b/Tests/Logger/ElasticaLoggerTest.php
@@ -22,8 +22,7 @@ class ElasticaLoggerTest extends \PHPUnit_Framework_TestCase
/**
* @param string $level
* @param string $message
- * @param array $context
- *
+ * @param array $context
* @return ElasticaLogger
*/
private function getMockLoggerForLevelMessageAndContext($level, $message, $context)
@@ -46,7 +45,7 @@ class ElasticaLoggerTest extends \PHPUnit_Framework_TestCase
public function testGetZeroIfNoQueriesAdded()
{
- $elasticaLogger = new ElasticaLogger();
+ $elasticaLogger = new ElasticaLogger;
$this->assertEquals(0, $elasticaLogger->getNbQueries());
}
diff --git a/Tests/Manager/RepositoryManagerTest.php b/Tests/Manager/RepositoryManagerTest.php
index 71bb076..8849035 100644
--- a/Tests/Manager/RepositoryManagerTest.php
+++ b/Tests/Manager/RepositoryManagerTest.php
@@ -4,19 +4,16 @@ namespace FOS\ElasticaBundle\Tests\Manager;
use FOS\ElasticaBundle\Manager\RepositoryManager;
-class CustomRepository
-{
-}
+class CustomRepository{}
-class Entity
-{
-}
+class Entity{}
/**
* @author Richard Miller
*/
class RepositoryManagerTest extends \PHPUnit_Framework_TestCase
{
+
public function testThatGetRepositoryReturnsDefaultRepository()
{
/** @var $finderMock \PHPUnit_Framework_MockObject_MockObject|\FOS\ElasticaBundle\Finder\TransformedFinder */
diff --git a/Tests/Persister/ObjectPersisterTest.php b/Tests/Persister/ObjectPersisterTest.php
index 06039f0..497c286 100644
--- a/Tests/Persister/ObjectPersisterTest.php
+++ b/Tests/Persister/ObjectPersisterTest.php
@@ -31,6 +31,13 @@ class InvalidObjectPersister extends ObjectPersister
class ObjectPersisterTest extends \PHPUnit_Framework_TestCase
{
+ public function setUp()
+ {
+ if (!class_exists('Elastica\Type')) {
+ $this->markTestSkipped('The Elastica library classes are not available');
+ }
+ }
+
public function testThatCanReplaceObject()
{
$transformer = $this->getTransformer();
@@ -40,7 +47,10 @@ class ObjectPersisterTest extends \PHPUnit_Framework_TestCase
->disableOriginalConstructor()
->getMock();
$typeMock->expects($this->once())
- ->method('updateDocuments');
+ ->method('deleteById')
+ ->with($this->equalTo(123));
+ $typeMock->expects($this->once())
+ ->method('addDocument');
$fields = array('name' => array());
@@ -81,7 +91,7 @@ class ObjectPersisterTest extends \PHPUnit_Framework_TestCase
$typeMock->expects($this->never())
->method('deleteById');
$typeMock->expects($this->once())
- ->method('addDocuments');
+ ->method('addDocument');
$fields = array('name' => array());
@@ -120,7 +130,7 @@ class ObjectPersisterTest extends \PHPUnit_Framework_TestCase
->disableOriginalConstructor()
->getMock();
$typeMock->expects($this->once())
- ->method('deleteDocuments');
+ ->method('deleteById');
$typeMock->expects($this->never())
->method('addDocument');
@@ -203,7 +213,7 @@ class ObjectPersisterTest extends \PHPUnit_Framework_TestCase
private function getTransformer()
{
$transformer = new ModelToElasticaAutoTransformer();
- $transformer->setPropertyAccessor(PropertyAccess::createPropertyAccessor());
+ $transformer->setPropertyAccessor(PropertyAccess::getPropertyAccessor());
return $transformer;
}
diff --git a/Tests/Persister/ObjectSerializerPersisterTest.php b/Tests/Persister/ObjectSerializerPersisterTest.php
index 0536d06..aae3a64 100644
--- a/Tests/Persister/ObjectSerializerPersisterTest.php
+++ b/Tests/Persister/ObjectSerializerPersisterTest.php
@@ -2,7 +2,9 @@
namespace FOS\ElasticaBundle\Tests\ObjectSerializerPersister;
+use FOS\ElasticaBundle\Persister\ObjectPersister;
use FOS\ElasticaBundle\Persister\ObjectSerializerPersister;
+use FOS\ElasticaBundle\Transformer\ModelToElasticaAutoTransformer;
use FOS\ElasticaBundle\Transformer\ModelToElasticaIdentifierTransformer;
use Symfony\Component\PropertyAccess\PropertyAccess;
@@ -24,6 +26,13 @@ class POPO
class ObjectSerializerPersisterTest extends \PHPUnit_Framework_TestCase
{
+ public function setUp()
+ {
+ if (!class_exists('Elastica\Type')) {
+ $this->markTestSkipped('The Elastica library classes are not available');
+ }
+ }
+
public function testThatCanReplaceObject()
{
$transformer = $this->getTransformer();
@@ -33,7 +42,10 @@ class ObjectSerializerPersisterTest extends \PHPUnit_Framework_TestCase
->disableOriginalConstructor()
->getMock();
$typeMock->expects($this->once())
- ->method('updateDocuments');
+ ->method('deleteById')
+ ->with($this->equalTo(123));
+ $typeMock->expects($this->once())
+ ->method('addDocument');
$serializerMock = $this->getMockBuilder('FOS\ElasticaBundle\Serializer\Callback')->getMock();
$serializerMock->expects($this->once())->method('serialize');
@@ -53,7 +65,7 @@ class ObjectSerializerPersisterTest extends \PHPUnit_Framework_TestCase
$typeMock->expects($this->never())
->method('deleteById');
$typeMock->expects($this->once())
- ->method('addDocuments');
+ ->method('addDocument');
$serializerMock = $this->getMockBuilder('FOS\ElasticaBundle\Serializer\Callback')->getMock();
$serializerMock->expects($this->once())->method('serialize');
@@ -71,7 +83,7 @@ class ObjectSerializerPersisterTest extends \PHPUnit_Framework_TestCase
->disableOriginalConstructor()
->getMock();
$typeMock->expects($this->once())
- ->method('deleteDocuments');
+ ->method('deleteById');
$typeMock->expects($this->never())
->method('addDocument');
@@ -112,7 +124,7 @@ class ObjectSerializerPersisterTest extends \PHPUnit_Framework_TestCase
private function getTransformer()
{
$transformer = new ModelToElasticaIdentifierTransformer();
- $transformer->setPropertyAccessor(PropertyAccess::createPropertyAccessor());
+ $transformer->setPropertyAccessor(PropertyAccess::getPropertyAccessor());
return $transformer;
}
diff --git a/Tests/Provider/IndexableTest.php b/Tests/Provider/IndexableTest.php
deleted file mode 100644
index e122ec1..0000000
--- a/Tests/Provider/IndexableTest.php
+++ /dev/null
@@ -1,123 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace FOS\ElasticaBundle\Tests\Provider;
-
-use FOS\ElasticaBundle\Provider\Indexable;
-use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
-
-class IndexableTest extends \PHPUnit_Framework_TestCase
-{
- public $container;
-
- public function testIndexableUnknown()
- {
- $indexable = new Indexable(array(), $this->container);
- $index = $indexable->isObjectIndexable('index', 'type', new Entity());
-
- $this->assertTrue($index);
- }
-
- /**
- * @dataProvider provideIsIndexableCallbacks
- */
- public function testValidIndexableCallbacks($callback, $return)
- {
- $indexable = new Indexable(array(
- 'index/type' => $callback,
- ), $this->container);
- $index = $indexable->isObjectIndexable('index', 'type', new Entity());
-
- $this->assertEquals($return, $index);
- }
-
- /**
- * @dataProvider provideInvalidIsIndexableCallbacks
- * @expectedException \InvalidArgumentException
- */
- public function testInvalidIsIndexableCallbacks($callback)
- {
- $indexable = new Indexable(array(
- 'index/type' => $callback,
- ), $this->container);
- $indexable->isObjectIndexable('index', 'type', new Entity());
- }
-
- public function provideInvalidIsIndexableCallbacks()
- {
- return array(
- array('nonexistentEntityMethod'),
- array(array('@indexableService', 'internalMethod')),
- array(array(new IndexableDecider(), 'internalMethod')),
- array(42),
- array('entity.getIsIndexable() && nonexistentEntityFunction()'),
- );
- }
-
- public function provideIsIndexableCallbacks()
- {
- return array(
- array('isIndexable', false),
- array(array(new IndexableDecider(), 'isIndexable'), true),
- array(array('@indexableService', 'isIndexable'), true),
- array(array('@indexableService'), true),
- array(function (Entity $entity) { return $entity->maybeIndex(); }, true),
- array('entity.maybeIndex()', true),
- array('!object.isIndexable() && entity.property == "abc"', true),
- array('entity.property != "abc"', false),
- array('["array", "values"]', true),
- array('[]', false)
- );
- }
-
- protected function setUp()
- {
- $this->container = $this->getMockBuilder('Symfony\\Component\\DependencyInjection\\ContainerInterface')
- ->getMock();
-
- $this->container->expects($this->any())
- ->method('get')
- ->with('indexableService')
- ->will($this->returnValue(new IndexableDecider()));
- }
-}
-
-class Entity
-{
- public $property = 'abc';
-
- public function isIndexable()
- {
- return false;
- }
-
- public function maybeIndex()
- {
- return true;
- }
-}
-
-class IndexableDecider
-{
- public function isIndexable(Entity $entity)
- {
- return !$entity->isIndexable();
- }
-
- protected function internalMethod()
- {
- }
-
- public function __invoke($object)
- {
- return true;
- }
-}
diff --git a/Tests/RepositoryTest.php b/Tests/RepositoryTest.php
index 7702af2..c4d4efc 100644
--- a/Tests/RepositoryTest.php
+++ b/Tests/RepositoryTest.php
@@ -13,7 +13,14 @@ class RepositoryTest extends \PHPUnit_Framework_TestCase
{
$testQuery = 'Test Query';
- $finderMock = $this->getFinderMock($testQuery);
+ /** @var $typeMock \PHPUnit_Framework_MockObject_MockObject|\FOS\ElasticaBundle\Finder\TransformedFinder */
+ $finderMock = $this->getMockBuilder('FOS\ElasticaBundle\Finder\TransformedFinder')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $finderMock->expects($this->once())
+ ->method('find')
+ ->with($this->equalTo($testQuery));
+
$repository = new Repository($finderMock);
$repository->find($testQuery);
}
@@ -23,7 +30,14 @@ class RepositoryTest extends \PHPUnit_Framework_TestCase
$testQuery = 'Test Query';
$testLimit = 20;
- $finderMock = $this->getFinderMock($testQuery, $testLimit);
+ /** @var $typeMock \PHPUnit_Framework_MockObject_MockObject|\FOS\ElasticaBundle\Finder\TransformedFinder */
+ $finderMock = $this->getMockBuilder('FOS\ElasticaBundle\Finder\TransformedFinder')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $finderMock->expects($this->once())
+ ->method('find')
+ ->with($this->equalTo($testQuery), $this->equalTo($testLimit));
+
$repository = new Repository($finderMock);
$repository->find($testQuery, $testLimit);
}
@@ -32,7 +46,14 @@ class RepositoryTest extends \PHPUnit_Framework_TestCase
{
$testQuery = 'Test Query';
- $finderMock = $this->getFinderMock($testQuery, array(), 'findPaginated');
+ /** @var $typeMock \PHPUnit_Framework_MockObject_MockObject|\FOS\ElasticaBundle\Finder\TransformedFinder */
+ $finderMock = $this->getMockBuilder('FOS\ElasticaBundle\Finder\TransformedFinder')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $finderMock->expects($this->once())
+ ->method('findPaginated')
+ ->with($this->equalTo($testQuery));
+
$repository = new Repository($finderMock);
$repository->findPaginated($testQuery);
}
@@ -41,7 +62,14 @@ class RepositoryTest extends \PHPUnit_Framework_TestCase
{
$testQuery = 'Test Query';
- $finderMock = $this->getFinderMock($testQuery, array(), 'createPaginatorAdapter');
+ /** @var $typeMock \PHPUnit_Framework_MockObject_MockObject|\FOS\ElasticaBundle\Finder\TransformedFinder */
+ $finderMock = $this->getMockBuilder('FOS\ElasticaBundle\Finder\TransformedFinder')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $finderMock->expects($this->once())
+ ->method('createPaginatorAdapter')
+ ->with($this->equalTo($testQuery));
+
$repository = new Repository($finderMock);
$repository->createPaginatorAdapter($testQuery);
}
@@ -49,28 +77,17 @@ class RepositoryTest extends \PHPUnit_Framework_TestCase
public function testThatFindHybridCallsFindHybridOnFinder()
{
$testQuery = 'Test Query';
+ $testLimit = 20;
- $finderMock = $this->getFinderMock($testQuery, null, 'findHybrid');
- $repository = new Repository($finderMock);
- $repository->findHybrid($testQuery);
- }
-
- /**
- * @param string $testQuery
- * @param mixed $testLimit
- * @param string $method
- *
- * @return \FOS\ElasticaBundle\Finder\TransformedFinder
- */
- private function getFinderMock($testQuery, $testLimit = null, $method = 'find')
- {
+ /** @var $typeMock \PHPUnit_Framework_MockObject_MockObject|\FOS\ElasticaBundle\Finder\TransformedFinder */
$finderMock = $this->getMockBuilder('FOS\ElasticaBundle\Finder\TransformedFinder')
->disableOriginalConstructor()
->getMock();
$finderMock->expects($this->once())
- ->method($method)
+ ->method('findHybrid')
->with($this->equalTo($testQuery), $this->equalTo($testLimit));
- return $finderMock;
+ $repository = new Repository($finderMock);
+ $repository->findHybrid($testQuery, $testLimit);
}
}
diff --git a/Tests/Transformer/ElasticaToModelTransformerCollectionTest.php b/Tests/Transformer/ElasticaToModelTransformerCollectionTest.php
index 56a7200..eb4d8e4 100644
--- a/Tests/Transformer/ElasticaToModelTransformerCollectionTest.php
+++ b/Tests/Transformer/ElasticaToModelTransformerCollectionTest.php
@@ -37,7 +37,7 @@ class ElasticaToModelTransformerCollectionTest extends \PHPUnit_Framework_TestCa
$this->collection = new ElasticaToModelTransformerCollection($this->transformers = array(
'type1' => $transformer1,
'type2' => $transformer2,
- ));
+ ), array());
}
public function testGetObjectClass()
@@ -47,7 +47,7 @@ class ElasticaToModelTransformerCollectionTest extends \PHPUnit_Framework_TestCa
$objectClasses = $this->collection->getObjectClass();
$this->assertEquals(array(
'type1' => 'FOS\ElasticaBundle\Tests\Transformer\POPO',
- 'type2' => 'FOS\ElasticaBundle\Tests\Transformer\POPO2',
+ 'type2' => 'FOS\ElasticaBundle\Tests\Transformer\POPO2'
), $objectClasses);
}
@@ -89,8 +89,8 @@ class ElasticaToModelTransformerCollectionTest extends \PHPUnit_Framework_TestCa
$this->transformers['type1']->expects($this->once())
->method('transform')
- ->with(array($document1, $document2))
- ->will($this->returnValue(array($result1, $result2)));
+ ->with(array($document1,$document2))
+ ->will($this->returnValue(array($result1,$result2)));
$results = $this->collection->transform(array($document1, $document2));
@@ -120,8 +120,8 @@ class ElasticaToModelTransformerCollectionTest extends \PHPUnit_Framework_TestCa
return array(
array(
- $result, $transformedObject,
- ),
+ $result, $transformedObject
+ )
);
}
@@ -157,9 +157,6 @@ class POPO
public $id;
public $data;
- /**
- * @param integer $id
- */
public function __construct($id, $data)
{
$this->data = $data;
diff --git a/Tests/Transformer/ModelToElasticaAutoTransformerTest.php b/Tests/Transformer/ModelToElasticaAutoTransformerTest.php
index f45134e..1fa6a8e 100644
--- a/Tests/Transformer/ModelToElasticaAutoTransformerTest.php
+++ b/Tests/Transformer/ModelToElasticaAutoTransformerTest.php
@@ -2,7 +2,6 @@
namespace FOS\ElasticaBundle\Tests\Transformer\ModelToElasticaAutoTransformer;
-use FOS\ElasticaBundle\Event\TransformEvent;
use FOS\ElasticaBundle\Transformer\ModelToElasticaAutoTransformer;
use Symfony\Component\PropertyAccess\PropertyAccess;
@@ -22,8 +21,8 @@ class POPO
public function __construct()
{
$this->date = new \DateTime('1979-05-05');
- $this->file = new \SplFileInfo(__DIR__.'/../fixtures/attachment.odt');
- $this->fileContents = file_get_contents(__DIR__.'/../fixtures/attachment.odt');
+ $this->file = new \SplFileInfo(__DIR__ . '/../fixtures/attachment.odt');
+ $this->fileContents = file_get_contents(__DIR__ . '/../fixtures/attachment.odt');
}
public function getId()
@@ -48,7 +47,7 @@ class POPO
{
return array(
'key1' => 'value1',
- 'key2' => 'value2',
+ 'key2' => 'value2'
);
}
@@ -110,7 +109,7 @@ class POPO
public function getNestedObject()
{
- return array('key1' => (object) array('id' => 1, 'key1sub1' => 'value1sub1', 'key1sub2' => 'value1sub2'));
+ return array('key1' => (object)array('id' => 1, 'key1sub1' => 'value1sub1', 'key1sub2' => 'value1sub2'));
}
public function getUpper()
@@ -126,33 +125,11 @@ class POPO
class ModelToElasticaAutoTransformerTest extends \PHPUnit_Framework_TestCase
{
- public function testTransformerDispatches()
+ public function setUp()
{
- $dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')
- ->getMock();
- $dispatcher->expects($this->once())
- ->method('dispatch')
- ->with(
- TransformEvent::POST_TRANSFORM,
- $this->isInstanceOf('FOS\ElasticaBundle\Event\TransformEvent')
- );
-
- $transformer = $this->getTransformer($dispatcher);
- $transformer->transform(new POPO(), array());
- }
-
- public function testPropertyPath()
- {
- $transformer = $this->getTransformer();
-
- $document = $transformer->transform(new POPO(), array('name' => array('property_path' => false)));
- $this->assertInstanceOf('Elastica\Document', $document);
- $this->assertFalse($document->has('name'));
-
- $document = $transformer->transform(new POPO(), array('realName' => array('property_path' => 'name')));
- $this->assertInstanceOf('Elastica\Document', $document);
- $this->assertTrue($document->has('realName'));
- $this->assertEquals('someName', $document->get('realName'));
+ if (!class_exists('Elastica\Document')) {
+ $this->markTestSkipped('The Elastica library classes are not available');
+ }
}
public function testThatCanTransformObject()
@@ -175,7 +152,7 @@ class ModelToElasticaAutoTransformerTest extends \PHPUnit_Framework_TestCase
'float' => array(),
'bool' => array(),
'date' => array(),
- 'falseBool' => array(),
+ 'falseBool' => array()
)
);
$data = $document->getData();
@@ -208,7 +185,7 @@ class ModelToElasticaAutoTransformerTest extends \PHPUnit_Framework_TestCase
$this->assertEquals(
array(
'key1' => 'value1',
- 'key2' => 'value2',
+ 'key2' => 'value2'
), $data['array']
);
}
@@ -253,7 +230,7 @@ class ModelToElasticaAutoTransformerTest extends \PHPUnit_Framework_TestCase
$document = $transformer->transform(new POPO(), array('file' => array('type' => 'attachment')));
$data = $document->getData();
- $this->assertEquals(base64_encode(file_get_contents(__DIR__.'/../fixtures/attachment.odt')), $data['file']);
+ $this->assertEquals(base64_encode(file_get_contents(__DIR__ . '/../fixtures/attachment.odt')), $data['file']);
}
public function testFileContentsAddedForAttachmentMapping()
@@ -263,7 +240,7 @@ class ModelToElasticaAutoTransformerTest extends \PHPUnit_Framework_TestCase
$data = $document->getData();
$this->assertEquals(
- base64_encode(file_get_contents(__DIR__.'/../fixtures/attachment.odt')), $data['fileContents']
+ base64_encode(file_get_contents(__DIR__ . '/../fixtures/attachment.odt')), $data['fileContents']
);
}
@@ -271,18 +248,18 @@ class ModelToElasticaAutoTransformerTest extends \PHPUnit_Framework_TestCase
{
$transformer = $this->getTransformer();
$document = $transformer->transform(new POPO(), array(
- 'sub' => array(
- 'type' => 'nested',
- 'properties' => array('foo' => array()),
- ),
- ));
+ 'sub' => array(
+ 'type' => 'nested',
+ 'properties' => array('foo' => '~')
+ )
+ ));
$data = $document->getData();
$this->assertTrue(array_key_exists('sub', $data));
$this->assertInternalType('array', $data['sub']);
$this->assertEquals(array(
array('foo' => 'foo'),
- array('foo' => 'bar'),
+ array('foo' => 'bar')
), $data['sub']);
}
@@ -292,8 +269,8 @@ class ModelToElasticaAutoTransformerTest extends \PHPUnit_Framework_TestCase
$document = $transformer->transform(new POPO(), array(
'sub' => array(
'type' => 'object',
- 'properties' => array('bar'),
- ),
+ 'properties' => array('bar')
+ )
));
$data = $document->getData();
@@ -301,7 +278,7 @@ class ModelToElasticaAutoTransformerTest extends \PHPUnit_Framework_TestCase
$this->assertInternalType('array', $data['sub']);
$this->assertEquals(array(
array('bar' => 'foo'),
- array('bar' => 'bar'),
+ array('bar' => 'bar')
), $data['sub']);
}
@@ -310,18 +287,18 @@ class ModelToElasticaAutoTransformerTest extends \PHPUnit_Framework_TestCase
$transformer = $this->getTransformer();
$document = $transformer->transform(new POPO(), array(
'obj' => array(
- 'type' => 'object',
- ),
+ 'type' => 'object'
+ )
));
$data = $document->getData();
$this->assertTrue(array_key_exists('obj', $data));
$this->assertInternalType('array', $data['obj']);
$this->assertEquals(array(
- 'foo' => 'foo',
- 'bar' => 'foo',
- 'id' => 1,
- ), $data['obj']);
+ 'foo' => 'foo',
+ 'bar' => 'foo',
+ 'id' => 1
+ ), $data['obj']);
}
public function testObjectsMappingOfAtLeastOneAutoMappedObjectAndAtLeastOneManuallyMappedObject()
@@ -336,14 +313,14 @@ class ModelToElasticaAutoTransformerTest extends \PHPUnit_Framework_TestCase
'properties' => array(
'key1sub1' => array(
'type' => 'string',
- 'properties' => array(),
+ 'properties' => array()
),
'key1sub2' => array(
'type' => 'string',
- 'properties' => array(),
- ),
- ),
- ),
+ 'properties' => array()
+ )
+ )
+ )
)
);
$data = $document->getData();
@@ -356,14 +333,14 @@ class ModelToElasticaAutoTransformerTest extends \PHPUnit_Framework_TestCase
array(
'foo' => 'foo',
'bar' => 'foo',
- 'id' => 1,
+ 'id' => 1
),
$data['obj']
);
$this->assertEquals(
array(
'key1sub1' => 'value1sub1',
- 'key1sub2' => 'value1sub2',
+ 'key1sub2' => 'value1sub2'
),
$data['nestedObject'][0]
);
@@ -373,7 +350,7 @@ class ModelToElasticaAutoTransformerTest extends \PHPUnit_Framework_TestCase
{
$transformer = $this->getTransformer();
$document = $transformer->transform(new POPO(), array(
- '_parent' => array('type' => 'upper', 'property' => 'upper', 'identifier' => 'id'),
+ '_parent' => array('type' => 'upper', 'property'=>'upper', 'identifier' => 'id'),
));
$this->assertEquals("parent", $document->getParent());
@@ -383,7 +360,7 @@ class ModelToElasticaAutoTransformerTest extends \PHPUnit_Framework_TestCase
{
$transformer = $this->getTransformer();
$document = $transformer->transform(new POPO(), array(
- '_parent' => array('type' => 'upper', 'property' => 'upper', 'identifier' => 'name'),
+ '_parent' => array('type' => 'upper', 'property'=>'upper', 'identifier' => 'name'),
));
$this->assertEquals("a random name", $document->getParent());
@@ -393,7 +370,7 @@ class ModelToElasticaAutoTransformerTest extends \PHPUnit_Framework_TestCase
{
$transformer = $this->getTransformer();
$document = $transformer->transform(new POPO(), array(
- '_parent' => array('type' => 'upper', 'property' => null, 'identifier' => 'id'),
+ '_parent' => array('type' => 'upper', 'property'=>null, 'identifier' => 'id'),
));
$this->assertEquals("parent", $document->getParent());
@@ -403,21 +380,19 @@ class ModelToElasticaAutoTransformerTest extends \PHPUnit_Framework_TestCase
{
$transformer = $this->getTransformer();
$document = $transformer->transform(new POPO(), array(
- '_parent' => array('type' => 'upper', 'property' => 'upperAlias', 'identifier' => 'id'),
+ '_parent' => array('type' => 'upper', 'property'=>'upperAlias', 'identifier' => 'id'),
));
$this->assertEquals("parent", $document->getParent());
}
/**
- * @param null|\Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher
- *
* @return ModelToElasticaAutoTransformer
*/
- private function getTransformer($dispatcher = null)
+ private function getTransformer()
{
- $transformer = new ModelToElasticaAutoTransformer(array(), $dispatcher);
- $transformer->setPropertyAccessor(PropertyAccess::createPropertyAccessor());
+ $transformer = new ModelToElasticaAutoTransformer();
+ $transformer->setPropertyAccessor(PropertyAccess::getPropertyAccessor());
return $transformer;
}
diff --git a/Tests/Transformer/ModelToElasticaIdentifierTransformerTest.php b/Tests/Transformer/ModelToElasticaIdentifierTransformerTest.php
index aa3d7b7..f1a77d4 100644
--- a/Tests/Transformer/ModelToElasticaIdentifierTransformerTest.php
+++ b/Tests/Transformer/ModelToElasticaIdentifierTransformerTest.php
@@ -23,6 +23,13 @@ class POPO
class ModelToElasticaIdentifierTransformerTest extends \PHPUnit_Framework_TestCase
{
+ public function setUp()
+ {
+ if (!class_exists('Elastica\Document')) {
+ $this->markTestSkipped('The Elastica library classes are not available');
+ }
+ }
+
public function testGetDocumentWithIdentifierOnly()
{
$transformer = $this->getTransformer();
@@ -51,7 +58,7 @@ class ModelToElasticaIdentifierTransformerTest extends \PHPUnit_Framework_TestCa
private function getTransformer()
{
$transformer = new ModelToElasticaIdentifierTransformer();
- $transformer->setPropertyAccessor(PropertyAccess::createPropertyAccessor());
+ $transformer->setPropertyAccessor(PropertyAccess::getPropertyAccessor());
return $transformer;
}
diff --git a/Tests/bootstrap.php b/Tests/bootstrap.php
new file mode 100644
index 0000000..30fb165
--- /dev/null
+++ b/Tests/bootstrap.php
@@ -0,0 +1,19 @@
+
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace FOS\ElasticaBundle\Transformer;
-
-use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
-
-abstract class AbstractElasticaToModelTransformer implements ElasticaToModelTransformerInterface
-{
- /**
- * PropertyAccessor instance.
- *
- * @var PropertyAccessorInterface
- */
- protected $propertyAccessor;
-
- /**
- * Set the PropertyAccessor instance.
- *
- * @param PropertyAccessorInterface $propertyAccessor
- */
- public function setPropertyAccessor(PropertyAccessorInterface $propertyAccessor)
- {
- $this->propertyAccessor = $propertyAccessor;
- }
-
- /**
- * Returns a sorting closure to be used with usort() to put retrieved objects
- * back in the order that they were returned by ElasticSearch.
- *
- * @param array $idPos
- * @param string $identifierPath
- * @return callable
- */
- protected function getSortingClosure(array $idPos, $identifierPath)
- {
- $propertyAccessor = $this->propertyAccessor;
-
- return function ($a, $b) use ($idPos, $identifierPath, $propertyAccessor) {
- return $idPos[$propertyAccessor->getValue($a, $identifierPath)] > $idPos[$propertyAccessor->getValue($b, $identifierPath)];
- };
- }
-}
diff --git a/Transformer/CombinedResultTransformer.php b/Transformer/CombinedResultTransformer.php
new file mode 100644
index 0000000..50822ae
--- /dev/null
+++ b/Transformer/CombinedResultTransformer.php
@@ -0,0 +1,71 @@
+
+ */
+class CombinedResultTransformer
+{
+ /**
+ * @var \FOS\ElasticaBundle\Type\TypeConfiguration
+ */
+ private $configurations;
+
+ /**
+ * @var ResultTransformerInterface
+ */
+ private $transformer;
+
+ /**
+ * @param \FOS\ElasticaBundle\Type\TypeConfiguration[] $configurations
+ * @param ResultTransformerInterface $transformer
+ */
+ public function __construct(array $configurations, ResultTransformerInterface $transformer)
+ {
+ $this->configurations = $configurations;
+ $this->transformer = $transformer;
+ }
+
+ /**
+ * Transforms Elastica results into Models.
+ *
+ * @param TransformingResult[] $results
+ * @return object[]
+ */
+ public function transform($results)
+ {
+ $grouped = array();
+
+ foreach ($results as $result) {
+ $grouped[$result->getType()][] = $result;
+ }
+
+ foreach ($grouped as $type => $group) {
+ $this->transformer->transform($this->getConfiguration($type), $group);
+ }
+ }
+
+ /**
+ * Retrieves the transformer for a given type.
+ *
+ * @param string $type
+ * @return \FOS\ElasticaBundle\Type\TypeConfiguration
+ * @throws \InvalidArgumentException
+ */
+ private function getConfiguration($type)
+ {
+ if (!array_key_exists($type, $this->configurations)) {
+ throw new \InvalidArgumentException(sprintf(
+ 'Configuration for type "%s" is not registered with this combined transformer.',
+ $type
+ ));
+ }
+
+ return $this->configurations[$type];
+ }
+}
diff --git a/Transformer/ElasticaToModelTransformerCollection.php b/Transformer/ElasticaToModelTransformerCollection.php
index 9920f43..f65f8db 100644
--- a/Transformer/ElasticaToModelTransformerCollection.php
+++ b/Transformer/ElasticaToModelTransformerCollection.php
@@ -41,7 +41,6 @@ class ElasticaToModelTransformerCollection implements ElasticaToModelTransformer
/**
* @param Document[] $elasticaObjects
- *
* @return array
*/
public function transform(array $elasticaObjects)
@@ -52,12 +51,12 @@ class ElasticaToModelTransformerCollection implements ElasticaToModelTransformer
}
$transformed = array();
- foreach ($sorted as $type => $objects) {
+ foreach ($sorted AS $type => $objects) {
$transformedObjects = $this->transformers[$type]->transform($objects);
- $identifierGetter = 'get'.ucfirst($this->transformers[$type]->getIdentifierField());
+ $identifierGetter = 'get' . ucfirst($this->transformers[$type]->getIdentifierField());
$transformed[$type] = array_combine(
array_map(
- function ($o) use ($identifierGetter) {
+ function($o) use ($identifierGetter) {
return $o->$identifierGetter();
},
$transformedObjects
@@ -81,7 +80,7 @@ class ElasticaToModelTransformerCollection implements ElasticaToModelTransformer
$objects = $this->transform($elasticaObjects);
$result = array();
- for ($i = 0, $j = count($elasticaObjects); $i < $j; $i++) {
+ for ($i = 0; $i < count($elasticaObjects); $i++) {
$result[] = new HybridResult($elasticaObjects[$i], $objects[$i]);
}
diff --git a/Transformer/ElasticaToModelTransformerInterface.php b/Transformer/ElasticaToModelTransformerInterface.php
index 71cd651..5635ef3 100644
--- a/Transformer/ElasticaToModelTransformerInterface.php
+++ b/Transformer/ElasticaToModelTransformerInterface.php
@@ -3,33 +3,32 @@
namespace FOS\ElasticaBundle\Transformer;
/**
- * Maps Elastica documents with model objects.
+ * Maps Elastica documents with model objects
*/
interface ElasticaToModelTransformerInterface
{
/**
* Transforms an array of elastica objects into an array of
- * model objects fetched from the doctrine repository.
+ * model objects fetched from the doctrine repository
*
* @param array $elasticaObjects array of elastica objects
- *
* @return array of model objects
**/
- public function transform(array $elasticaObjects);
+ function transform(array $elasticaObjects);
- public function hybridTransform(array $elasticaObjects);
+ function hybridTransform(array $elasticaObjects);
/**
* Returns the object class used by the transformer.
*
* @return string
*/
- public function getObjectClass();
+ function getObjectClass();
/**
- * Returns the identifier field from the options.
+ * Returns the identifier field from the options
*
* @return string the identifier field
*/
- public function getIdentifierField();
+ function getIdentifierField();
}
diff --git a/Transformer/HighlightableModelInterface.php b/Transformer/HighlightableModelInterface.php
index 96c6c7c..d55407e 100644
--- a/Transformer/HighlightableModelInterface.php
+++ b/Transformer/HighlightableModelInterface.php
@@ -1,23 +1,16 @@
- 'id',
+ 'identifier' => 'id'
);
/**
- * PropertyAccessor instance.
+ * PropertyAccessor instance
*
* @var PropertyAccessorInterface
*/
protected $propertyAccessor;
/**
- * Instanciates a new Mapper.
+ * Instanciates a new Mapper
*
- * @param array $options
- * @param EventDispatcherInterface $dispatcher
+ * @param array $options
*/
- public function __construct(array $options = array(), EventDispatcherInterface $dispatcher = null)
+ public function __construct(array $options = array())
{
$this->options = array_merge($this->options, $options);
- $this->dispatcher = $dispatcher;
}
/**
- * Set the PropertyAccessor.
+ * Set the PropertyAccessor
*
* @param PropertyAccessorInterface $propertyAccessor
*/
@@ -58,7 +49,7 @@ class ModelToElasticaAutoTransformer implements ModelToElasticaTransformerInterf
}
/**
- * Transforms an object into an elastica object having the required keys.
+ * Transforms an object into an elastica object having the required keys
*
* @param object $object the object to convert
* @param array $fields the keys we want to have in the returned array
@@ -72,27 +63,19 @@ class ModelToElasticaAutoTransformer implements ModelToElasticaTransformerInterf
foreach ($fields as $key => $mapping) {
if ($key == '_parent') {
- $property = (null !== $mapping['property']) ? $mapping['property'] : $mapping['type'];
+ $property = (null !== $mapping['property'])?$mapping['property']:$mapping['type'];
$value = $this->propertyAccessor->getValue($object, $property);
$document->setParent($this->propertyAccessor->getValue($value, $mapping['identifier']));
-
continue;
}
- $path = isset($mapping['property_path']) ?
- $mapping['property_path'] :
- $key;
- if (false === $path) {
- continue;
- }
- $value = $this->propertyAccessor->getValue($object, $path);
+ $value = $this->propertyAccessor->getValue($object, $key);
if (isset($mapping['type']) && in_array($mapping['type'], array('nested', 'object')) && isset($mapping['properties']) && !empty($mapping['properties'])) {
/* $value is a nested document or object. Transform $value into
* an array of documents, respective the mapped properties.
*/
$document->set($key, $this->transformNested($value, $mapping['properties']));
-
continue;
}
@@ -103,28 +86,20 @@ class ModelToElasticaAutoTransformer implements ModelToElasticaTransformerInterf
} else {
$document->addFileContent($key, $value);
}
-
continue;
}
$document->set($key, $this->normalizeValue($value));
}
- if ($this->dispatcher) {
- $event = new TransformEvent($document, $fields, $object);
- $this->dispatcher->dispatch(TransformEvent::POST_TRANSFORM, $event);
-
- $document = $event->getDocument();
- }
-
return $document;
}
/**
- * transform a nested document or an object property into an array of ElasticaDocument.
+ * transform a nested document or an object property into an array of ElasticaDocument
*
* @param array|\Traversable|\ArrayAccess $objects the object to convert
- * @param array $fields the keys we want to have in the returned array
+ * @param array $fields the keys we want to have in the returned array
*
* @return array
*/
@@ -148,7 +123,7 @@ class ModelToElasticaAutoTransformer implements ModelToElasticaTransformerInterf
}
/**
- * Attempts to convert any type to a string or an array of strings.
+ * Attempts to convert any type to a string or an array of strings
*
* @param mixed $value
*
@@ -156,16 +131,17 @@ class ModelToElasticaAutoTransformer implements ModelToElasticaTransformerInterf
*/
protected function normalizeValue($value)
{
- $normalizeValue = function (&$v) {
+ $normalizeValue = function(&$v)
+ {
if ($v instanceof \DateTime) {
$v = $v->format('c');
} elseif (!is_scalar($v) && !is_null($v)) {
- $v = (string) $v;
+ $v = (string)$v;
}
};
if (is_array($value) || $value instanceof \Traversable || $value instanceof \ArrayAccess) {
- $value = is_array($value) ? $value : iterator_to_array($value, false);
+ $value = is_array($value) ? $value : iterator_to_array($value);
array_walk_recursive($value, $normalizeValue);
} else {
$normalizeValue($value);
diff --git a/Transformer/ModelToElasticaIdentifierTransformer.php b/Transformer/ModelToElasticaIdentifierTransformer.php
index 6301be1..654850f 100644
--- a/Transformer/ModelToElasticaIdentifierTransformer.php
+++ b/Transformer/ModelToElasticaIdentifierTransformer.php
@@ -6,12 +6,12 @@ use Elastica\Document;
/**
* Creates an Elastica document with the ID of
- * the Doctrine object as Elastica document ID.
+ * the Doctrine object as Elastica document ID
*/
class ModelToElasticaIdentifierTransformer extends ModelToElasticaAutoTransformer
{
/**
- * Creates an elastica document with the id of the doctrine object as id.
+ * Creates an elastica document with the id of the doctrine object as id
*
* @param object $object the object to convert
* @param array $fields the keys we want to have in the returned array
@@ -21,7 +21,6 @@ class ModelToElasticaIdentifierTransformer extends ModelToElasticaAutoTransforme
public function transform($object, array $fields)
{
$identifier = $this->propertyAccessor->getValue($object, $this->options['identifier']);
-
return new Document($identifier);
}
}
diff --git a/Transformer/ModelToElasticaTransformerInterface.php b/Transformer/ModelToElasticaTransformerInterface.php
index 0ad9f12..ec9ada3 100644
--- a/Transformer/ModelToElasticaTransformerInterface.php
+++ b/Transformer/ModelToElasticaTransformerInterface.php
@@ -3,17 +3,16 @@
namespace FOS\ElasticaBundle\Transformer;
/**
- * Maps Elastica documents with model objects.
+ * Maps Elastica documents with model objects
*/
interface ModelToElasticaTransformerInterface
{
/**
- * Transforms an object into an elastica object having the required keys.
+ * Transforms an object into an elastica object having the required keys
*
* @param object $object the object to convert
- * @param array $fields the keys we want to have in the returned array
- *
+ * @param array $fields the keys we want to have in the returned array
* @return \Elastica\Document
**/
- public function transform($object, array $fields);
+ function transform($object, array $fields);
}
diff --git a/Transformer/ResultTransformer.php b/Transformer/ResultTransformer.php
new file mode 100644
index 0000000..31a4b9f
--- /dev/null
+++ b/Transformer/ResultTransformer.php
@@ -0,0 +1,79 @@
+lookupManager = $lookupManager;
+ $this->propertyAccessor = $propertyAccessor;
+ }
+
+ /**
+ * Transforms Elastica results into Models.
+ *
+ * @param TypeConfiguration $configuration
+ * @param \FOS\ElasticaBundle\Elastica\TransformingResult[] $results
+ * @throws \FOS\ElasticaBundle\Exception\MissingModelException
+ * @throws \FOS\ElasticaBundle\Exception\UnexpectedObjectException
+ */
+ public function transform(TypeConfiguration $configuration, $results)
+ {
+ $results = $this->processResults($results);
+ $lookup = $this->lookupManager->getLookup($configuration->getType());
+ $objects = $lookup->lookup($configuration, array_keys($results));
+
+ if (!$configuration->isIgnoreMissing() and count($objects) < count($results)) {
+ throw new MissingModelException(count($objects), count($results));
+ }
+
+ $identifierProperty = $configuration->getIdentifierProperty();
+ foreach ($objects as $object) {
+ $id = $this->propertyAccessor->getValue($object, $identifierProperty);
+
+ if (!array_key_exists($id, $results)) {
+ throw new UnexpectedObjectException($id);
+ }
+
+ $results[$id]->setTransformed($object);
+ }
+ }
+
+ /**
+ * Processes the results array into a more usable format for the transformation.
+ *
+ * @param \FOS\ElasticaBundle\Elastica\TransformingResult[] $results
+ * @return \FOS\ElasticaBundle\Elastica\TransformingResult[]
+ */
+ private function processResults($results)
+ {
+ $sorted = array();
+ foreach ($results as $result) {
+ $sorted[$result->getId()] = $result;
+ }
+
+ return $sorted;
+ }
+}
diff --git a/Transformer/ResultTransformerInterface.php b/Transformer/ResultTransformerInterface.php
new file mode 100644
index 0000000..ebce242
--- /dev/null
+++ b/Transformer/ResultTransformerInterface.php
@@ -0,0 +1,16 @@
+
+ */
+interface LookupInterface
+{
+ /**
+ * Returns the lookup key.
+ *
+ * @return string
+ */
+ public function getKey();
+
+ /**
+ * Look up objects of a specific type with ids as supplied.
+ *
+ * @param TypeConfiguration $configuration
+ * @param int[] $ids
+ * @return object[]
+ */
+ public function lookup(TypeConfiguration $configuration, array $ids);
+}
diff --git a/Type/LookupManager.php b/Type/LookupManager.php
new file mode 100644
index 0000000..15a7dc6
--- /dev/null
+++ b/Type/LookupManager.php
@@ -0,0 +1,35 @@
+lookups[$lookup->getKey()] = $lookup;
+ }
+ }
+
+ /**
+ * @param string $type
+ * @return LookupInterface
+ * @throws \InvalidArgumentException
+ */
+ public function getLookup($type)
+ {
+ if (!array_key_exists($type, $this->lookups)) {
+ throw new \InvalidArgumentException(sprintf('Lookup with key "%s" does not exist', $type));
+ }
+
+ return $this->lookups[$type];
+ }
+}
diff --git a/Type/TypeConfiguration.php b/Type/TypeConfiguration.php
new file mode 100644
index 0000000..6a9ff0d
--- /dev/null
+++ b/Type/TypeConfiguration.php
@@ -0,0 +1,102 @@
+
+ */
+final class TypeConfiguration
+{
+ /**
+ * The identifier property that is used to retrieve an identifier from the model.
+ *
+ * @var string
+ */
+ private $identifierProperty;
+
+ /**
+ * Returns the fully qualified class for the model that this type represents.
+ *
+ * @var string
+ */
+ private $modelClass;
+
+ /**
+ * Returns the repository method that will create a query builder or associated
+ * query object for lookup purposes.
+ *
+ * @var string
+ */
+ private $repositoryMethod;
+
+ /**
+ * Returns the name of the type.
+ *
+ * @var string
+ */
+ private $type;
+
+ /**
+ * If the lookup should hydrate models to objects or leave data as an array.
+ *
+ * @var bool
+ */
+ private $hydrate = true;
+
+ /**
+ * If the type should ignore missing results from a lookup.
+ *
+ * @var bool
+ */
+ private $ignoreMissing = false;
+
+ /**
+ * @return boolean
+ */
+ public function isHydrate()
+ {
+ return $this->hydrate;
+ }
+
+ /**
+ * @return string
+ */
+ public function getIdentifierProperty()
+ {
+ return $this->identifierProperty;
+ }
+
+ /**
+ * @return boolean
+ */
+ public function isIgnoreMissing()
+ {
+ return $this->ignoreMissing;
+ }
+
+ /**
+ * @return string
+ */
+ public function getModelClass()
+ {
+ return $this->modelClass;
+ }
+
+ /**
+ * @return string
+ */
+ public function getRepositoryMethod()
+ {
+ return $this->repositoryMethod;
+ }
+
+ /**
+ * @return string
+ */
+ public function getType()
+ {
+ return $this->type;
+ }
+}
diff --git a/composer.json b/composer.json
index 9705a04..e827ac6 100644
--- a/composer.json
+++ b/composer.json
@@ -6,39 +6,43 @@
"homepage": "https://github.com/FriendsOfSymfony/FOSElasticaBundle",
"license": "MIT",
"authors": [
- { "name": "FriendsOfSymfony Community", "homepage": "https://github.com/FriendsOfSymfony/FOSElasticaBundle/contributors" },
- { "name": "Tim Nagel", "email": "tim@nagel.com.au" },
+ { "name": "Thibault Duplessis", "email": "thibault.duplessis@gmail.com" },
{ "name": "Richard Miller", "email": "richard.miller@limethinking.co.uk" },
{ "name": "Jeremy Mikola", "email": "jmikola@gmail.com" }
],
"require": {
"php": ">=5.3.2",
+ "doctrine/inflector": "~1.0",
"symfony/framework-bundle": "~2.3",
"symfony/console": "~2.1",
"symfony/form": "~2.1",
"symfony/property-access": "~2.2",
- "ruflin/elastica": ">=0.90.10.0, <1.5-dev",
+ "ruflin/elastica": ">=0.90.2.0, <1.1-dev",
"psr/log": "~1.0"
},
"require-dev":{
- "doctrine/orm": "~2.4",
- "doctrine/doctrine-bundle": "~1.2",
- "jms/serializer-bundle": "@stable",
- "phpunit/phpunit": "~4.1",
+ "doctrine/orm": ">=2.2,<2.5-dev",
+ "doctrine/mongodb-odm": "1.0.*@dev",
"propel/propel1": "1.6.*",
- "pagerfanta/pagerfanta": "~1.0",
- "knplabs/knp-components": "~1.2",
- "knplabs/knp-paginator-bundle": "~2.4",
- "symfony/browser-kit" : "~2.3",
- "symfony/expression-language" : "~2.4",
- "symfony/twig-bundle": "~2.3"
+ "pagerfanta/pagerfanta": "1.0.*@dev",
+ "knplabs/knp-components": "1.2.*",
+ "symfony/expression-language" : "2.4.*@dev"
+ },
+ "suggest": {
+ "doctrine/orm": ">=2.2,<2.5-dev",
+ "doctrine/mongodb-odm": "1.0.*@dev",
+ "propel/propel1": "1.6.*",
+ "pagerfanta/pagerfanta": "1.0.*@dev",
+ "knplabs/knp-components": "1.2.*",
+ "symfony/expression-language" : "2.4.*@dev"
},
"autoload": {
- "psr-4": { "FOS\\ElasticaBundle\\": "" }
+ "psr-0": { "FOS\\ElasticaBundle": "" }
},
+ "target-dir": "FOS/ElasticaBundle",
"extra": {
"branch-alias": {
- "dev-master": "3.2.x-dev"
+ "dev-master": "3.0.x-dev"
}
}
}
diff --git a/phpunit.xml.dist b/phpunit.xml.dist
index 799d5bf..005cfd8 100644
--- a/phpunit.xml.dist
+++ b/phpunit.xml.dist
@@ -1,6 +1,6 @@
-
+
./Tests