Merge pull request #277 from FriendsOfSymfony/namespace_compat

Compatibility with Elastica 0.20.x (incl. Serializer support)
This commit is contained in:
Jeremy Mikola 2013-04-26 16:12:30 -07:00
commit be3c2779ef
28 changed files with 301 additions and 128 deletions

View file

@ -2,13 +2,13 @@
namespace FOS\ElasticaBundle;
use Elastica_Client;
use Elastica\Client as ElasticaClient;
use FOS\ElasticaBundle\Logger\ElasticaLogger;
/**
* @author Gordon Franke <info@nevalon.de>
*/
class Client extends Elastica_Client
class Client extends ElasticaClient
{
/**
* @var ElasticaLogger
@ -20,7 +20,7 @@ class Client extends Elastica_Client
$this->logger = $logger;
}
public function request($path, $method, $data = array(), array $query = array())
public function request($path, $method = Request::GET, $data = array(), array $query = array())
{
$start = microtime(true);
$response = parent::request($path, $method, $data, $query);

View file

@ -8,8 +8,8 @@ use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\Output;
use Elastica_Query;
use Elastica_Result;
use Elastica\Query;
use Elastica\Result;
/**
* Searches a type
@ -41,11 +41,11 @@ class SearchCommand extends ContainerAwareCommand
protected function execute(InputInterface $input, OutputInterface $output)
{
$indexName = $input->getOption('index');
/** @var $index \Elastica_Index */
/** @var $index \Elastica\Index */
$index = $this->getContainer()->get('fos_elastica.index_manager')->getIndex($indexName ? $indexName : null);
$type = $index->getType($input->getArgument('type'));
$query = Elastica_Query::create($input->getArgument('query'));
$query->setLimit($input->getOption('limit'));
$query = Query::create($input->getArgument('query'));
$query->setSize($input->getOption('limit'));
if ($input->getOption('explain')) {
$query->setExplain(true);
}
@ -58,7 +58,7 @@ class SearchCommand extends ContainerAwareCommand
}
}
protected function formatResult(Elastica_Result $result, $showField, $showSource, $showId, $explain)
protected function formatResult(Result $result, $showField, $showSource, $showId, $explain)
{
$source = $result->getSource();
if ($showField) {

View file

@ -34,6 +34,13 @@ class Configuration implements ConfigurationInterface
->scalarNode('default_client')->end()
->scalarNode('default_index')->end()
->scalarNode('default_manager')->defaultValue('orm')->end()
->arrayNode('serializer')
->treatNullLike(array())
->children()
->scalarNode('callback_class')->defaultValue('FOS\ElasticaBundle\Serializer\Callback')->end()
->scalarNode('serializer')->defaultValue('serializer')->end()
->end()
->end()
->end()
;
@ -205,6 +212,16 @@ class Configuration implements ConfigurationInterface
->prototype('array')
->treatNullLike(array())
->children()
->arrayNode('serializer')
->addDefaultsIfNotSet()
->children()
->arrayNode('groups')
->treatNullLike(array())
->prototype('scalar')->end()
->end()
->scalarNode('version')->end()
->end()
->end()
->scalarNode('index_analyzer')->end()
->scalarNode('search_analyzer')->end()
->arrayNode('persistence')

View file

@ -40,7 +40,8 @@ class FOSElasticaExtension extends Extension
}
$clientIdsByName = $this->loadClients($config['clients'], $container);
$indexIdsByName = $this->loadIndexes($config['indexes'], $container, $clientIdsByName, $config['default_client']);
$serializerConfig = isset($config['serializer']) ? $config['serializer'] : null;
$indexIdsByName = $this->loadIndexes($config['indexes'], $container, $clientIdsByName, $config['default_client'], $serializerConfig);
$indexRefsByName = array_map(function($id) {
return new Reference($id);
}, $indexIdsByName);
@ -93,7 +94,7 @@ class FOSElasticaExtension extends Extension
* @throws \InvalidArgumentException
* @return array
*/
protected function loadIndexes(array $indexes, ContainerBuilder $container, array $clientIdsByName, $defaultClientName)
protected function loadIndexes(array $indexes, ContainerBuilder $container, array $clientIdsByName, $defaultClientName, $serializerConfig)
{
$indexIds = array();
foreach ($indexes as $name => $index) {
@ -128,7 +129,7 @@ class FOSElasticaExtension extends Extension
if (!empty($index['settings'])) {
$this->indexConfigs[$name]['config']['settings'] = $index['settings'];
}
$this->loadTypes(isset($index['types']) ? $index['types'] : array(), $container, $name, $indexId, $typePrototypeConfig);
$this->loadTypes(isset($index['types']) ? $index['types'] : array(), $container, $name, $indexId, $typePrototypeConfig, $serializerConfig);
}
return $indexIds;
@ -169,7 +170,7 @@ class FOSElasticaExtension extends Extension
* @param $indexId
* @param array $typePrototypeConfig
*/
protected function loadTypes(array $types, ContainerBuilder $container, $indexName, $indexId, array $typePrototypeConfig)
protected function loadTypes(array $types, ContainerBuilder $container, $indexName, $indexId, array $typePrototypeConfig, $serializerConfig)
{
foreach ($types as $name => $type) {
$type = self::deepArrayUnion($typePrototypeConfig, $type);
@ -178,6 +179,23 @@ class FOSElasticaExtension extends Extension
$typeDef = new Definition('%fos_elastica.type.class%', $typeDefArgs);
$typeDef->setFactoryService($indexId);
$typeDef->setFactoryMethod('getType');
if ($serializerConfig) {
$callbackDef = new Definition($serializerConfig['callback_class']);
$callbackId = sprintf('%s.%s.serializer.callback', $indexId, $name);
$typeDef->addMethodCall('setSerializer', array(array(new Reference($callbackId), 'serialize')));
$callbackDef->addMethodCall('setSerializer', array(new Reference($serializerConfig['serializer'])));
if (isset($type['serializer']['groups'])) {
$callbackDef->addMethodCall('setGroups', array($type['serializer']['groups']));
}
if (isset($type['serializer']['version'])) {
$callbackDef->addMethodCall('setVersion', array($type['serializer']['version']));
}
$container->setDefinition($callbackId, $callbackDef);
$typeDef->addMethodCall('setSerializer', array(array(new Reference($callbackId), 'serialize')));
}
$container->setDefinition($typeId, $typeDef);
if (isset($type['_source'])) {
$this->indexConfigs[$indexName]['config']['mappings'][$name]['_source'] = $type['_source'];

View file

@ -7,7 +7,7 @@ interface FinderInterface
/**
* Searches for query results within a given limit
*
* @param mixed $query Can be a string, an array or an Elastica_Query object
* @param mixed $query Can be a string, an array or an \Elastica\Query object
* @param int $limit How many results to get
* @return array results
*/

View file

@ -4,14 +4,14 @@ namespace FOS\ElasticaBundle\Finder;
use FOS\ElasticaBundle\Paginator\PaginatorAdapterInterface;
use Pagerfanta\Pagerfanta;
use Elastica_Query;
use Elastica\Query;
interface PaginatedFinderInterface extends FinderInterface
{
/**
* Searches for query results and returns them wrapped in a paginator
*
* @param mixed $query Can be a string, an array or an Elastica_Query object
* @param mixed $query Can be a string, an array or an \Elastica\Query object
* @return Pagerfanta paginated results
*/
function findPaginated($query);

View file

@ -7,8 +7,8 @@ use FOS\ElasticaBundle\Transformer\ElasticaToModelTransformerInterface;
use FOS\ElasticaBundle\Paginator\TransformedPaginatorAdapter;
use FOS\ElasticaBundle\Paginator\FantaPaginatorAdapter;
use Pagerfanta\Pagerfanta;
use Elastica_Searchable;
use Elastica_Query;
use Elastica\SearchableInterface;
use Elastica\Query;
/**
* Finds elastica documents and map them to persisted objects
@ -18,7 +18,7 @@ class TransformedFinder implements PaginatedFinderInterface
protected $searchable;
protected $transformer;
public function __construct(Elastica_Searchable $searchable, ElasticaToModelTransformerInterface $transformer)
public function __construct(SearchableInterface $searchable, ElasticaToModelTransformerInterface $transformer)
{
$this->searchable = $searchable;
$this->transformer = $transformer;
@ -52,9 +52,9 @@ class TransformedFinder implements PaginatedFinderInterface
*/
protected function search($query, $limit = null)
{
$queryObject = Elastica_Query::create($query);
$queryObject = Query::create($query);
if (null !== $limit) {
$queryObject->setLimit($limit);
$queryObject->setSize($limit);
}
$results = $this->searchable->search($queryObject)->getResults();
@ -70,7 +70,7 @@ class TransformedFinder implements PaginatedFinderInterface
*/
public function findPaginated($query)
{
$queryObject = Elastica_Query::create($query);
$queryObject = Query::create($query);
$paginatorAdapter = $this->createPaginatorAdapter($queryObject);
return new Pagerfanta(new FantaPaginatorAdapter($paginatorAdapter));
@ -81,7 +81,7 @@ class TransformedFinder implements PaginatedFinderInterface
*/
public function createPaginatorAdapter($query)
{
$query = Elastica_Query::create($query);
$query = Query::create($query);
return new TransformedPaginatorAdapter($this->searchable, $query, $this->transformer);
}
}

View file

@ -2,14 +2,14 @@
namespace FOS\ElasticaBundle;
use Elastica_Result;
use Elastica\Result;
class HybridResult
{
protected $result;
protected $transformed;
public function __construct(Elastica_Result $result, $transformed = null)
public function __construct(Result $result, $transformed = null)
{
$this->result = $result;
$this->transformed = $transformed;

View file

@ -2,6 +2,8 @@
namespace FOS\ElasticaBundle;
use Elastica\Index;
class IndexManager
{
protected $indexesByName;
@ -11,9 +13,9 @@ class IndexManager
* Constructor.
*
* @param array $indexesByName
* @param \Elastica_Index $defaultIndex
* @param Index $defaultIndex
*/
public function __construct(array $indexesByName, \Elastica_Index $defaultIndex)
public function __construct(array $indexesByName, Index $defaultIndex)
{
$this->indexesByName = $indexesByName;
$this->defaultIndexName = $defaultIndex->getName();
@ -33,7 +35,7 @@ class IndexManager
* Gets an index by its name
*
* @param string $name Index to return, or the default index if null
* @return \Elastica_Index
* @return Index
* @throws \InvalidArgumentException if no index exists for the given name
*/
public function getIndex($name = null)
@ -52,7 +54,7 @@ class IndexManager
/**
* Gets the default index
*
* @return \Elastica_Index
* @return Index
*/
public function getDefaultIndex()
{

View file

@ -2,35 +2,35 @@
namespace FOS\ElasticaBundle\Paginator;
use Elastica_Searchable;
use Elastica_Query;
use Elastica_ResultSet;
use Elastica\SearchableInterface;
use Elastica\Query;
use Elastica\ResultSet;
use FOS\ElasticaBundle\Paginator\PaginatorAdapterInterface;
use FOS\ElasticaBundle\Paginator\RawPartialResults;
use FOS\ElasticaBundle\Paginator\PartialResultsInterface;
/**
* Allows pagination of Elastica_Query. Does not map results
* Allows pagination of Elastica\Query. Does not map results
*/
class RawPaginatorAdapter implements PaginatorAdapterInterface
{
/**
* @var Elastica_Searchable the object to search in
* @var SearchableInterface the object to search in
*/
private $searchable = null;
/**
* @var Elastica_Query the query to search
* @var Query the query to search
*/
private $query = null;
/**
* @see PaginatorAdapterInterface::__construct
*
* @param Elastica_Searchable $searchable the object to search in
* @param Elastica_Query $query the query to search
* @param SearchableInterface $searchable the object to search in
* @param Query $query the query to search
*/
public function __construct(Elastica_Searchable $searchable, Elastica_Query $query)
public function __construct(SearchableInterface $searchable, Query $query)
{
$this->searchable = $searchable;
$this->query = $query;
@ -41,7 +41,7 @@ class RawPaginatorAdapter implements PaginatorAdapterInterface
*
* @param $offset
* @param $itemCountPerPage
* @return Elastica_ResultSet
* @return ResultSet
*/
protected function getElasticaResults($offset, $itemCountPerPage)
{

View file

@ -3,8 +3,8 @@
namespace FOS\ElasticaBundle\Paginator;
use FOS\ElasticaBundle\Paginator\PartialResultsInterface;
use Elastica_ResultSet;
use Elastica_Result;
use Elastica\ResultSet;
use Elastica\Result;
/**
* Raw partial results transforms to a simple array
@ -14,9 +14,9 @@ class RawPartialResults implements PartialResultsInterface
protected $resultSet;
/**
* @param \Elastica_ResultSet $resultSet
* @param ResultSet $resultSet
*/
public function __construct(Elastica_ResultSet $resultSet)
public function __construct(ResultSet $resultSet)
{
$this->resultSet = $resultSet;
}
@ -26,7 +26,7 @@ class RawPartialResults implements PartialResultsInterface
*/
public function toArray()
{
return array_map(function(Elastica_Result $result) {
return array_map(function(Result $result) {
return $result->getSource();
}, $this->resultSet->getResults());
}

View file

@ -4,22 +4,22 @@ namespace FOS\ElasticaBundle\Paginator;
use FOS\ElasticaBundle\Transformer\ElasticaToModelTransformerInterface;
use FOS\ElasticaBundle\Paginator\TransformedPartialResults;
use Elastica_Searchable;
use Elastica_Query;
use Elastica\SearchableInterface;
use Elastica\Query;
/**
* Allows pagination of Elastica_Query
* Allows pagination of \Elastica\Query
*/
class TransformedPaginatorAdapter extends RawPaginatorAdapter
{
private $transformer;
/**
* @param Elastica_Searchable $searchable the object to search in
* @param Elastica_Query $query the query to search
* @param SearchableInterface $searchable the object to search in
* @param Query $query the query to search
* @param ElasticaToModelTransformerInterface $transformer the transformer for fetching the results
*/
public function __construct(Elastica_Searchable $searchable, Elastica_Query $query, ElasticaToModelTransformerInterface $transformer)
public function __construct(SearchableInterface $searchable, Query $query, ElasticaToModelTransformerInterface $transformer)
{
parent::__construct($searchable, $query);

View file

@ -4,7 +4,7 @@ namespace FOS\ElasticaBundle\Paginator;
use FOS\ElasticaBundle\Transformer\ElasticaToModelTransformerInterface;
use FOS\ElasticaBundle\Paginator\RawPartialResults;
use Elastica_ResultSet;
use Elastica\ResultSet;
/**
* Partial transformed result set
@ -14,10 +14,10 @@ class TransformedPartialResults extends RawPartialResults
protected $transformer;
/**
* @param \Elastica_ResultSet $resultSet
* @param ResultSet $resultSet
* @param \FOS\ElasticaBundle\Transformer\ElasticaToModelTransformerInterface $transformer
*/
public function __construct(Elastica_ResultSet $resultSet, ElasticaToModelTransformerInterface $transformer)
public function __construct(ResultSet $resultSet, ElasticaToModelTransformerInterface $transformer)
{
parent::__construct($resultSet);

View file

@ -3,8 +3,8 @@
namespace FOS\ElasticaBundle\Persister;
use FOS\ElasticaBundle\Transformer\ModelToElasticaTransformerInterface;
use Elastica_Type;
use Elastica_Document;
use Elastica\Type;
use Elastica\Document;
/**
* Inserts, replaces and deletes single documents in an elastica type
@ -19,7 +19,7 @@ class ObjectPersister implements ObjectPersisterInterface
protected $objectClass;
protected $fields;
public function __construct(Elastica_Type $type, ModelToElasticaTransformerInterface $transformer, $objectClass, array $fields)
public function __construct(Type $type, ModelToElasticaTransformerInterface $transformer, $objectClass, array $fields)
{
$this->type = $type;
$this->transformer = $transformer;
@ -95,7 +95,7 @@ class ObjectPersister implements ObjectPersisterInterface
* Transforms an object to an elastica document
*
* @param object $object
* @return Elastica_Document the elastica document
* @return Document the elastica document
*/
public function transformToElasticaDocument($object)
{

View file

@ -2,6 +2,7 @@
namespace FOS\ElasticaBundle\Propel;
use Elastica\Document;
use FOS\ElasticaBundle\HybridResult;
use FOS\ElasticaBundle\Transformer\ElasticaToModelTransformerInterface;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
@ -65,12 +66,12 @@ class ElasticaToModelTransformer implements ElasticaToModelTransformerInterface
* Transforms an array of elastica objects into an array of
* model objects fetched from the propel repository
*
* @param \Elastica_Document[] $elasticaObjects array of elastica objects
* @param Document[] $elasticaObjects array of elastica objects
* @return array
*/
public function transform(array $elasticaObjects)
{
$ids = array_map(function(\Elastica_Document $elasticaObject) {
$ids = array_map(function(Document $elasticaObject) {
return $elasticaObject->getId();
}, $elasticaObjects);

119
README.md
View file

@ -58,6 +58,31 @@ Most of the time, you will need only one.
clients:
default: { host: localhost, port: 9200 }
#### Declare a serializer
Elastica can handle objects instead of data arrays if a serializer callable is configured
#app/config/config.yml
fos_elastica:
clients:
default: { host: localhost, port: 9200 }
serializer:
callback_class: callback_class
serializer: serializer
``callback_class`` is the name of a class having a public method serialize($object) and should
extends from ``FOS\ElasticaBundle\Serializer\Callback``.
``serializer`` is the service id for the actual serializer, e.g. ``serializer`` if you're using
JMSSerializerBundle. If this is configured you can use ``\Elastica\Type::addObject`` instead of
``\Elastica\Type::addDocument`` to add data to the index. The bundle provides a default implementation
with a serializer service id 'serializer' that can be turned on by adding the following line to your config.
#app/config/config.yml
fos_elastica:
serializer: ~
#### Declare an index
Elasticsearch index is comparable to Doctrine entity manager.
@ -66,13 +91,16 @@ Most of the time, you will need only one.
fos_elastica:
clients:
default: { host: localhost, port: 9200 }
serializer:
callback_class: FOS\ElasticaBundle\Serializer\Callback
id: serializer
indexes:
website:
client: default
Here we created a "website" index, that uses our "default" client.
Our index is now available as a service: `fos_elastica.index.website`. It is an instance of `Elastica_Index`.
Our index is now available as a service: `fos_elastica.index.website`. It is an instance of `\Elastica\Index`.
If you need to have different index name from the service name, for example,
in order to have different indexes for different environments then you can
@ -96,6 +124,9 @@ Elasticsearch type is comparable to Doctrine entity repository.
fos_elastica:
clients:
default: { host: localhost, port: 9200 }
serializer:
callback_class: FOS\ElasticaBundle\Serializer\Callback
id: serializer
indexes:
website:
client: default
@ -107,13 +138,40 @@ Elasticsearch type is comparable to Doctrine entity repository.
lastName: { boost: 3 }
aboutMe: ~
Our type is now available as a service: `fos_elastica.index.website.user`. It is an instance of `Elastica_Type`.
Our type is now available as a service: `fos_elastica.index.website.user`. It is an instance of `\Elastica\Type`.
### Declaring serializer groups
If you are using the JMSSerializerBundle for serializing objects passed to elastica you can define serializer groups
per type.
fos_elastica:
clients:
default: { host: localhost, port: 9200 }
serializer:
callback_class: %classname%
id: serializer
indexes:
website:
client: default
types:
user:
mappings:
username: { boost: 5 }
firstName: { boost: 3 }
lastName: { boost: 3 }
aboutMe:
serializer:
groups: [elastica, Default]
### Declaring parent field
fos_elastica:
clients:
default: { host: localhost, port: 9200 }
serializer:
callback_class_class: FOS\ElasticaBundle\Serializer\Callback
id: serializer
indexes:
website:
client: default
@ -129,6 +187,9 @@ Our type is now available as a service: `fos_elastica.index.website.user`. It is
fos_elastica:
clients:
default: { host: localhost, port: 9200 }
serializer:
callback_class: FOS\ElasticaBundle\Serializer\Callback
id: serializer
indexes:
website:
client: default
@ -164,6 +225,9 @@ some configuration will let ElasticaBundle do it for us.
fos_elastica:
clients:
default: { host: localhost, port: 9200 }
serializer:
callback_class: FOS\ElasticaBundle\Serializer\Callback
id: serializer
indexes:
website:
client: default
@ -232,13 +296,14 @@ Its class must implement `FOS\ElasticaBundle\Provider\ProviderInterface`.
namespace Acme\UserBundle\Provider;
use FOS\ElasticaBundle\Provider\ProviderInterface;
use Elastica_Type;
use Elastica\Type;
use Elastica\Document;
class UserProvider implements ProviderInterface
{
protected $userType;
public function __construct(Elastica_Type $userType)
public function __construct(Type $userType)
{
$this->userType = $userType;
}
@ -254,7 +319,7 @@ Its class must implement `FOS\ElasticaBundle\Provider\ProviderInterface`.
$loggerClosure('Indexing users');
}
$document = new \Elastica_Document();
$document = new Document();
$document->setData(array('username' => 'Bob'));
$this->userType->addDocuments(array($document));
}
@ -266,10 +331,10 @@ You will find a more complete implementation example in `src/FOS/ElasticaBundle/
You can just use the index and type Elastica objects, provided as services, to perform searches.
/** var Elastica_Type */
/** var Elastica\Type */
$userType = $this->container->get('fos_elastica.index.website.user');
/** var Elastica_ResultSet */
/** var Elastica\ResultSet */
$resultSet = $userType->search('bob');
#### Doctrine/Propel finder
@ -281,6 +346,9 @@ Declare that you want a Doctrine/Propel finder in your configuration:
fos_elastica:
clients:
default: { host: localhost, port: 9200 }
serializer:
callback_class: FOS\ElasticaBundle\Serializer\Callback
id: serializer
indexes:
website:
client: default
@ -318,7 +386,7 @@ Knp paginator:
$userPaginator = $paginator->paginate($finder->createPaginatorAdapter('bob'));
You can also get both the Elastica results and the entities together from the finder.
You can then access the score, highlights etc. from the Elastica_Result whilst
You can then access the score, highlights etc. from the Elastica\Result whilst
still also getting the entity.
/** var array of FOS\ElasticaBundle\HybridResult */
@ -328,7 +396,7 @@ still also getting the entity.
/** var Acme\UserBundle\Entity\User */
$user = $hybridResult->getTransformed();
/** var Elastica_Result */
/** var Elastica\Result */
$result = $hybridResult->getResult();
}
@ -509,28 +577,28 @@ You can also choose to only listen for some of the events:
If you use listeners to update your index, you may need to validate your
entities before you index them (e.g. only index "public" entities). Typically,
you'll want the listener to be consistent with the provider's query criteria.
This may be achieved by using the `is_indexable_callback` config parameter:
This may be achieved by using the `is_indexable_callback_class` config parameter:
persistence:
listener:
is_indexable_callback: "isPublic"
is_indexable_callback_class: "isPublic"
If `is_indexable_callback` is a string and the entity has a method with the
If `is_indexable_callback_class` is a string and the entity has a method with the
specified name, the listener will only index entities for which the method
returns `true`. Additionally, you may provide a service and method name pair:
persistence:
listener:
is_indexable_callback: [ "%custom_service_id%", "isIndexable" ]
is_indexable_callback_class: [ "%custom_service_id%", "isIndexable" ]
In this case, the callback will be the `isIndexable()` method on the specified
In this case, the callback_class will be the `isIndexable()` method on the specified
service and the object being considered for indexing will be passed as the only
argument. This allows you to do more complex validation (e.g. ACL checks).
As you might expect, new entities will only be indexed if the callback returns
As you might expect, new entities will only be indexed if the callback_class returns
`true`. Additionally, modified entities will be updated or removed from the
index depending on whether the callback returns `true` or `false`, respectively.
The delete listener disregards the callback.
index depending on whether the callback_class returns `true` or `false`, respectively.
The delete listener disregards the callback_class.
> **Propel** doesn't support this feature yet.
@ -563,7 +631,7 @@ Any setting can be specified when declaring a type. For example, to enable a cus
By default, exceptions from the Elastica client library will propagate through
the bundle's Client class. For instance, if the elasticsearch server is offline,
issuing a request will result in an `Elastica_Exception_Client` being thrown.
issuing a request will result in an `Elastica\Exception\Connection` being thrown.
Depending on your needs, it may be desirable to suppress these exceptions and
allow searches to fail silently.
@ -579,14 +647,17 @@ namespace Acme\ElasticaBundle;
use FOS\ElasticaBundle\Client as BaseClient;
use Elastica\Exception\ExceptionInterface;
use Elastica\Response;
class Client extends BaseClient
{
public function request($path, $method, $data = array())
{
try {
return parent::request($path, $method, $data);
} catch (\Elastica_Exception_Abstract $e) {
return new \Elastica_Response('{"took":0,"timed_out":false,"hits":{"total":0,"max_score":0,"hits":[]}}');
} catch (ExceptionInterface $e) {
return new Response('{"took":0,"timed_out":false,"hits":{"total":0,"max_score":0,"hits":[]}}');
}
}
}
@ -604,18 +675,18 @@ apply to queries against the `title` field.
```php
$finder = $this->container->get('fos_elastica.finder.website.article');
$boolQuery = new \Elastica_Query_Bool();
$boolQuery = new \Elastica\Query\Bool();
$fieldQuery = new \Elastica_Query_Text();
$fieldQuery = new \Elastica\Query\Text();
$fieldQuery->setFieldQuery('title', 'I am a title string');
$fieldQuery->setFieldParam('title', 'analyzer', 'my_analyzer');
$boolQuery->addShould($fieldQuery);
$tagsQuery = new \Elastica_Query_Terms();
$tagsQuery = new \Elastica\Query\Terms();
$tagsQuery->setTerms('tags', array('tag1', 'tag2'));
$boolQuery->addShould($tagsQuery);
$categoryQuery = new \Elastica_Query_Terms();
$categoryQuery = new \Elastica\Query\Terms();
$categoryQuery->setTerms('categoryIds', array('1', '2', '3'));
$boolQuery->addMust($categoryQuery);

View file

@ -2,6 +2,8 @@
namespace FOS\ElasticaBundle;
use Elastica\Type\Mapping;
/**
* Deletes and recreates indexes
*/
@ -66,11 +68,11 @@ class Resetter
* create type mapping object
*
* @param array $indexConfig
* @return \Elastica_Type_Mapping
* @return Mapping
*/
protected function createMapping($indexConfig)
{
$mapping = \Elastica_Type_Mapping::create($indexConfig['properties']);
$mapping = Mapping::create($indexConfig['properties']);
foreach($indexConfig['properties'] as $type) {
if (!empty($type['_parent']) && $type['_parent'] !== '~') {

View file

@ -6,8 +6,8 @@
<parameters>
<parameter key="fos_elastica.client.class">FOS\ElasticaBundle\Client</parameter>
<parameter key="fos_elastica.index.class">Elastica_Index</parameter>
<parameter key="fos_elastica.type.class">Elastica_Type</parameter>
<parameter key="fos_elastica.index.class">Elastica\Index</parameter>
<parameter key="fos_elastica.type.class">Elastica\Type</parameter>
<parameter key="fos_elastica.logger.class">FOS\ElasticaBundle\Logger\ElasticaLogger</parameter>
<parameter key="fos_elastica.data_collector.class">FOS\ElasticaBundle\DataCollector\ElasticaDataCollector</parameter>
<parameter key="fos_elastica.manager.class">FOS\ElasticaBundle\Manager\RepositoryManager</parameter>
@ -77,8 +77,7 @@
<tag name="knp_paginator.subscriber" />
</service>
<service id="fos_elastica.property_accessor" class="%fos_elastica.property_accessor.class%">
</service>
<service id="fos_elastica.property_accessor" class="%fos_elastica.property_accessor.class%" />
</services>
</container>

60
Serializer/Callback.php Normal file
View file

@ -0,0 +1,60 @@
<?php
namespace FOS\ElasticaBundle\Serializer;
use JMS\Serializer\SerializationContext;
use JMS\Serializer\SerializerInterface;
class Callback
{
protected $serializer;
protected $groups;
protected $version;
public function setSerializer($serializer)
{
$this->serializer = $serializer;
if (!method_exists($this->serializer, 'serialize')) {
throw new \RuntimeException('The serializer must have a "serialize" method.');
}
}
public function setGroups(array $groups)
{
$this->groups = $groups;
if ($this->groups) {
if (!$this->serializer instanceof SerializerInterface) {
throw new \RuntimeException('Setting serialization groups requires using "JMS\Serializer\Serializer".');
}
}
}
public function setVersion($version)
{
$this->version = $version;
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 ? new SerializationContext() : array();
if ($this->groups) {
$context->setGroups($this->groups);
}
if ($this->version) {
$context->setVersion($this->version);
}
return $this->serializer->serialize($object, 'json', $context);
}
}

View file

@ -19,8 +19,8 @@ class IndexManagerTest extends \PHPUnit_Framework_TestCase
'index2' => 'test2',
);
/** @var $defaultIndex \PHPUnit_Framework_MockObject_MockObject|\Elastica_Index */
$defaultIndex = $this->getMockBuilder('Elastica_Index')
/** @var $defaultIndex \PHPUnit_Framework_MockObject_MockObject|\Elastica\Index */
$defaultIndex = $this->getMockBuilder('Elastica\Index')
->disableOriginalConstructor()
->getMock();

View file

@ -33,7 +33,7 @@ class ObjectPersisterTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
if (!class_exists('Elastica_Type')) {
if (!class_exists('Elastica\Type')) {
$this->markTestSkipped('The Elastica library classes are not available');
}
}
@ -42,8 +42,8 @@ class ObjectPersisterTest extends \PHPUnit_Framework_TestCase
{
$transformer = $this->getTransformer();
/** @var $typeMock \PHPUnit_Framework_MockObject_MockObject|\Elastica_Type */
$typeMock = $this->getMockBuilder('Elastica_Type')
/** @var $typeMock \PHPUnit_Framework_MockObject_MockObject|\Elastica\Type */
$typeMock = $this->getMockBuilder('Elastica\Type')
->disableOriginalConstructor()
->getMock();
$typeMock->expects($this->once())
@ -65,8 +65,8 @@ class ObjectPersisterTest extends \PHPUnit_Framework_TestCase
{
$transformer = $this->getTransformer();
/** @var $typeMock \PHPUnit_Framework_MockObject_MockObject|\Elastica_Type */
$typeMock = $this->getMockBuilder('Elastica_Type')
/** @var $typeMock \PHPUnit_Framework_MockObject_MockObject|\Elastica\Type */
$typeMock = $this->getMockBuilder('Elastica\Type')
->disableOriginalConstructor()
->getMock();
$typeMock->expects($this->never())
@ -84,8 +84,8 @@ class ObjectPersisterTest extends \PHPUnit_Framework_TestCase
{
$transformer = $this->getTransformer();
/** @var $typeMock \PHPUnit_Framework_MockObject_MockObject|\Elastica_Type */
$typeMock = $this->getMockBuilder('Elastica_Type')
/** @var $typeMock \PHPUnit_Framework_MockObject_MockObject|\Elastica\Type */
$typeMock = $this->getMockBuilder('Elastica\Type')
->disableOriginalConstructor()
->getMock();
$typeMock->expects($this->never())
@ -106,8 +106,8 @@ class ObjectPersisterTest extends \PHPUnit_Framework_TestCase
{
$transformer = $this->getTransformer();
/** @var $typeMock \PHPUnit_Framework_MockObject_MockObject|\Elastica_Type */
$typeMock = $this->getMockBuilder('Elastica_Type')
/** @var $typeMock \PHPUnit_Framework_MockObject_MockObject|\Elastica\Type */
$typeMock = $this->getMockBuilder('Elastica\Type')
->disableOriginalConstructor()
->getMock();
$typeMock->expects($this->never())
@ -125,8 +125,8 @@ class ObjectPersisterTest extends \PHPUnit_Framework_TestCase
{
$transformer = $this->getTransformer();
/** @var $typeMock \PHPUnit_Framework_MockObject_MockObject|\Elastica_Type */
$typeMock = $this->getMockBuilder('Elastica_Type')
/** @var $typeMock \PHPUnit_Framework_MockObject_MockObject|\Elastica\Type */
$typeMock = $this->getMockBuilder('Elastica\Type')
->disableOriginalConstructor()
->getMock();
$typeMock->expects($this->once())
@ -147,8 +147,8 @@ class ObjectPersisterTest extends \PHPUnit_Framework_TestCase
{
$transformer = $this->getTransformer();
/** @var $typeMock \PHPUnit_Framework_MockObject_MockObject|\Elastica_Type */
$typeMock = $this->getMockBuilder('Elastica_Type')
/** @var $typeMock \PHPUnit_Framework_MockObject_MockObject|\Elastica\Type */
$typeMock = $this->getMockBuilder('Elastica\Type')
->disableOriginalConstructor()
->getMock();
$typeMock->expects($this->never())
@ -166,8 +166,8 @@ class ObjectPersisterTest extends \PHPUnit_Framework_TestCase
{
$transformer = $this->getTransformer();
/** @var $typeMock \PHPUnit_Framework_MockObject_MockObject|\Elastica_Type */
$typeMock = $this->getMockBuilder('Elastica_Type')
/** @var $typeMock \PHPUnit_Framework_MockObject_MockObject|\Elastica\Type */
$typeMock = $this->getMockBuilder('Elastica\Type')
->disableOriginalConstructor()
->getMock();
$typeMock->expects($this->never())
@ -190,8 +190,8 @@ class ObjectPersisterTest extends \PHPUnit_Framework_TestCase
{
$transformer = $this->getTransformer();
/** @var $typeMock \PHPUnit_Framework_MockObject_MockObject|\Elastica_Type */
$typeMock = $this->getMockBuilder('Elastica_Type')
/** @var $typeMock \PHPUnit_Framework_MockObject_MockObject|\Elastica\Type */
$typeMock = $this->getMockBuilder('Elastica\Type')
->disableOriginalConstructor()
->getMock();
$typeMock->expects($this->never())

View file

@ -3,6 +3,7 @@
namespace FOS\ElasticaBundle\Tests\Resetter;
use FOS\ElasticaBundle\Resetter;
use Elastica\Type\Mapping;
class ResetterTest extends \PHPUnit_Framework_TestCase
{
@ -91,7 +92,7 @@ class ResetterTest extends \PHPUnit_Framework_TestCase
$type->expects($this->once())
->method('delete');
$mapping = \Elastica_Type_Mapping::create($this->indexConfigsByName['foo']['config']['mappings']['a']['properties']);
$mapping = Mapping::create($this->indexConfigsByName['foo']['config']['mappings']['a']['properties']);
$type->expects($this->once())
->method('setMapping')
->with($mapping);
@ -130,7 +131,7 @@ class ResetterTest extends \PHPUnit_Framework_TestCase
$type->expects($this->once())
->method('delete');
$mapping = \Elastica_Type_Mapping::create($this->indexConfigsByName['parent']['config']['mappings']['a']['properties']);
$mapping = Mapping::create($this->indexConfigsByName['parent']['config']['mappings']['a']['properties']);
$mapping->setParam('_parent', array('type' => 'b'));
$type->expects($this->once())
->method('setMapping')
@ -141,21 +142,21 @@ class ResetterTest extends \PHPUnit_Framework_TestCase
}
/**
* @return \Elastica_Index
* @return \Elastica\Index
*/
private function getMockElasticaIndex()
{
return $this->getMockBuilder('Elastica_Index')
return $this->getMockBuilder('Elastica\Index')
->disableOriginalConstructor()
->getMock();
}
/**
* @return \Elastica_Type
* @return \Elastica\Type
*/
private function getMockElasticaType()
{
return $this->getMockBuilder('Elastica_Type')
return $this->getMockBuilder('Elastica\Type')
->disableOriginalConstructor()
->getMock();
}

View file

@ -2,6 +2,7 @@
namespace FOS\ElasticaBundle\Tests\Transformer;
use Elastica\Document;
use FOS\ElasticaBundle\Transformer\ElasticaToModelTransformerCollection;
class ElasticaToModelTransformerCollectionTest extends \PHPUnit_Framework_TestCase
@ -53,8 +54,8 @@ class ElasticaToModelTransformerCollectionTest extends \PHPUnit_Framework_TestCa
{
$this->collectionSetup();
$document1 = new \Elastica_Document(123, array('data' => 'lots of data'), 'type1');
$document2 = new \Elastica_Document(124, array('data' => 'not so much data'), 'type2');
$document1 = new Document(123, array('data' => 'lots of data'), 'type1');
$document2 = new Document(124, array('data' => 'not so much data'), 'type2');
$result1 = new POPO(123, 'lots of data');
$result2 = new POPO2(124, 'not so much data');
@ -80,8 +81,8 @@ class ElasticaToModelTransformerCollectionTest extends \PHPUnit_Framework_TestCa
{
$this->collectionSetup();
$document1 = new \Elastica_Document(123, array('data' => 'lots of data'), 'type1');
$document2 = new \Elastica_Document(124, array('data' => 'not so much data'), 'type1');
$document1 = new Document(123, array('data' => 'lots of data'), 'type1');
$document2 = new Document(124, array('data' => 'not so much data'), 'type1');
$result1 = new POPO(123, 'lots of data');
$result2 = new POPO2(124, 'not so much data');

View file

@ -112,7 +112,7 @@ class ModelToElasticaAutoTransformerTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
if (!class_exists('Elastica_Document')) {
if (!class_exists('Elastica\Document')) {
;
$this->markTestSkipped('The Elastica library classes are not available');
}
@ -124,7 +124,7 @@ class ModelToElasticaAutoTransformerTest extends \PHPUnit_Framework_TestCase
$document = $transformer->transform(new POPO(), array('name' => array()));
$data = $document->getData();
$this->assertInstanceOf('Elastica_Document', $document);
$this->assertInstanceOf('Elastica\Document', $document);
$this->assertEquals(123, $document->getId());
$this->assertEquals('someName', $data['name']);
}
@ -143,7 +143,7 @@ class ModelToElasticaAutoTransformerTest extends \PHPUnit_Framework_TestCase
);
$data = $document->getData();
$this->assertInstanceOf('Elastica_Document', $document);
$this->assertInstanceOf('Elastica\Document', $document);
$this->assertEquals(123, $document->getId());
$this->assertEquals('someName', $data['name']);
$this->assertEquals(7.2, $data['float']);

View file

@ -3,7 +3,7 @@
namespace FOS\ElasticaBundle\Transformer;
use FOS\ElasticaBundle\HybridResult;
use Elastica_Document;
use Elastica\Document;
/**
* Holds a collection of transformers for an index wide transformation.
@ -40,7 +40,7 @@ class ElasticaToModelTransformerCollection implements ElasticaToModelTransformer
}
/**
* @param Elastica_Document[] $elasticaObjects
* @param Document[] $elasticaObjects
* @return array
*/
public function transform(array $elasticaObjects)

View file

@ -3,6 +3,7 @@
namespace FOS\ElasticaBundle\Transformer;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Elastica\Document;
/**
* Maps Elastica documents with Doctrine objects
@ -53,12 +54,12 @@ class ModelToElasticaAutoTransformer implements ModelToElasticaTransformerInterf
* @param object $object the object to convert
* @param array $fields the keys we want to have in the returned array
*
* @return \Elastica_Document
* @return Document
**/
public function transform($object, array $fields)
{
$identifier = $this->propertyAccessor->getValue($object, $this->options['identifier']);
$document = new \Elastica_Document($identifier);
$document = new Document($identifier);
foreach ($fields as $key => $mapping) {
$value = $this->propertyAccessor->getValue($object, $key);

View file

@ -12,7 +12,7 @@ interface ModelToElasticaTransformerInterface
*
* @param object $object the object to convert
* @param array $fields the keys we want to have in the returned array
* @return \Elastica_Document
* @return \Elastica\Document
**/
function transform($object, array $fields);
}

View file

@ -16,7 +16,7 @@
"symfony/console": ">=2.1.0,<2.3.0-dev",
"symfony/form": ">=2.1.0,<2.3.0-dev",
"symfony/property-access": "2.2.*",
"ruflin/elastica": "0.19.8"
"ruflin/elastica": "0.20.5.*@dev"
},
"require-dev":{
"doctrine/orm": ">=2.2,<2.5-dev",
@ -38,7 +38,7 @@
"target-dir": "FOS/ElasticaBundle",
"extra": {
"branch-alias": {
"dev-master": "2.1.x-dev"
"dev-master": "3.0.x-dev"
}
}
}