FOSElasticaBundle/Manager/RepositoryManager.php

85 lines
2.5 KiB
PHP
Raw Normal View History

<?php
namespace FOS\ElasticaBundle\Manager;
use Doctrine\Common\Annotations\Reader;
use FOS\ElasticaBundle\Finder\FinderInterface;
use RuntimeException;
2013-11-14 16:04:08 +01:00
/**
* @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)
{
2015-03-12 11:20:00 +01:00
$this->entities[$entityName] = array();
$this->entities[$entityName]['finder'] = $finder;
$this->entities[$entityName]['repositoryName'] = $repositoryName;
}
/**
2015-03-12 11:20:00 +01:00
* Return repository for entity.
*
* Returns custom repository if one specified otherwise
2013-04-26 14:15:57 +02:00
* returns a basic repository.
*/
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));
}
2012-01-25 13:42:02 +01:00
$repository = $this->createRepository($entityName);
$this->repositories[$entityName] = $repository;
return $repository;
}
2012-01-25 13:45:08 +01:00
protected function getRepositoryName($entityName)
{
2012-01-25 13:45:08 +01:00
if (isset($this->entities[$entityName]['repositoryName'])) {
return $this->entities[$entityName]['repositoryName'];
}
2012-01-25 13:45:08 +01:00
$refClass = new \ReflectionClass($entityName);
$annotation = $this->reader->getClassAnnotation($refClass, 'FOS\\ElasticaBundle\\Annotation\\Search');
if ($annotation) {
2012-01-25 13:45:08 +01:00
$this->entities[$entityName]['repositoryName']
= $annotation->repositoryClass;
2015-03-12 11:20:00 +01:00
return $annotation->repositoryClass;
}
return 'FOS\ElasticaBundle\Repository';
}
2014-08-24 11:50:56 +02:00
/**
* @param string $entityName
*/
2012-01-25 13:42:02 +01:00
private function createRepository($entityName)
{
2013-11-14 16:04:08 +01:00
if (!class_exists($repositoryName = $this->getRepositoryName($entityName))) {
2012-01-25 13:42:02 +01:00
throw new RuntimeException(sprintf('%s repository for %s does not exist', $repositoryName, $entityName));
}
2013-11-14 16:04:08 +01:00
2012-01-25 13:42:02 +01:00
return new $repositoryName($this->entities[$entityName]['finder']);
}
}