FOSElasticaBundle/Manager/RepositoryManager.php

82 lines
2.6 KiB
PHP
Raw Normal View History

<?php
2011-12-11 21:14:00 +01:00
namespace FOQ\ElasticaBundle\Manager;
use Doctrine\Common\Annotations\Reader;
2011-12-11 21:17:41 +01:00
use FOQ\ElasticaBundle\Finder\FinderInterface;
2011-12-11 21:14:00 +01:00
use FOQ\ElasticaBundle\Repository;
use RuntimeException;
/**
* @author Richard Miller <info@limethinking.co.uk>
*
* Allows retrieval of basic or custom repository for mapped Doctrine
* entities/documents.
*/
2011-12-11 21:17:41 +01:00
class RepositoryManager implements RepositoryManagerInterface
{
protected $entities = array();
protected $repositories = array();
protected $reader;
public function __construct(Reader $reader)
{
$this->reader = $reader;
}
2011-12-11 21:17:41 +01:00
public function addEntity($entityName, FinderInterface $finder, $repositoryName = null)
{
$this->entities[$entityName]= array();
$this->entities[$entityName]['finder'] = $finder;
$this->entities[$entityName]['repositoryName'] = $repositoryName;
}
/**
* Return repository for entity
*
* Returns custom repository if one specified otherwise
* returns a basic respository.
*/
public function getRepository($entityName)
{
if (isset($this->repositories[$entityName])) {
return $this->repositories[$entityName];
}
if (!isset($this->entities[$entityName])) {
throw new RuntimeException(sprintf('No search finder configured for %s', $entityName));
}
$this->setRepositoryFromAnnotation($entityName);
if (isset($this->entities[$entityName]['repositoryName'])) {
$repositoryName = $this->entities[$entityName]['repositoryName'];
if (!class_exists($repositoryName)) {
throw new RuntimeException(sprintf('%s repository for %s does not exist', $repositoryName, $entityName));
}
$repository = new $repositoryName($this->entities[$entityName]['finder']);
$this->repositories[$entityName] = $repository;
return $repository;
}
$repository = new Repository($this->entities[$entityName]['finder']);
$this->repositories[$entityName] = $repository;
return $repository;
}
private function setRepositoryFromAnnotation($realEntityName)
{
if (isset($this->entities[$realEntityName]['repositoryName'])) {
return;
}
$refClass = new \ReflectionClass($realEntityName);
$annotation = $this->reader->getClassAnnotation($refClass, 'FOQ\\ElasticaBundle\\Configuration\\Search');
if ($annotation) {
$this->entities[$realEntityName]['repositoryName']
= $annotation->repositoryClass;
}
}
}