FOSElasticaBundle/Manager/RepositoryManager.php
Richard Miller e678ce8cc6 Added configuring repository by annotation
Conflicts:

	Manager/RepositoryManager.php
	Resources/config/mongodb.xml
	Resources/config/orm.xml
	Tests/Manager/RepositoryManagerTest.php
2012-01-25 11:20:47 +00:00

82 lines
2.6 KiB
PHP

<?php
namespace FOQ\ElasticaBundle\Manager;
use Doctrine\Common\Annotations\Reader;
use FOQ\ElasticaBundle\Finder\FinderInterface;
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.
*/
class RepositoryManager implements RepositoryManagerInterface
{
protected $entities = array();
protected $repositories = array();
protected $reader;
public function __construct(Reader $reader)
{
$this->reader = $reader;
}
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;
}
}
}