FOSElasticaBundle/Provider/ProviderRegistry.php
Jeremy Mikola b360a36737 [Provider] Create ProviderRegistry service (BC break)
This introduces a registry service for persistence providers.

Previously, tagging one or more provider services would cause AddProviderPass to clobber the default providers created by the bundle's extension class. Now, the extension class tags its created providers and allows them to be registered via RegisterProvidersPass just like custom providers.

BC break: Custom providers tagged "foq_elastica.provider" must now specify a "type" attribute on their tag. An "index" attribute is optional (the default ES index will be used by default).
2012-03-12 12:07:51 -04:00

99 lines
2.7 KiB
PHP

<?php
namespace FOQ\ElasticaBundle\Provider;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* References persistence providers for each index and type.
*/
class ProviderRegistry implements ContainerAwareInterface
{
private $container;
private $providers = array();
/**
* Registers a provider for the specified index and type.
*
* @param string $index
* @param string $type
* @param string $providerId
*/
public function addProvider($index, $type, $providerId)
{
if (!isset($this->providers[$index])) {
$this->providers[$index] = array();
}
$this->providers[$index][$type] = $providerId;
}
/**
* Gets all registered providers.
*
* @return array of ProviderInterface instances
*/
public function getAllProviders()
{
$providers = array();
foreach ($this->providers as $indexProviders) {
foreach ($indexProviders as $providerId) {
$providers[] = $this->container->get($providerId);
}
}
return $providers;
}
/**
* Gets all providers for an index.
*
* @param string $index
* @return array of ProviderInterface instances
* @throws InvalidArgumentException if no providers were registered for the index
*/
public function getIndexProviders($index)
{
if (!isset($this->providers[$index])) {
throw new \InvalidArgumentException(sprintf('No providers were registered for index "%s".', $index));
}
$providers = array();
foreach ($this->providers[$index] as $providerId) {
$providers[] = $this->container->get($providerId);
}
return $providers;
}
/**
* Gets the provider for an index and type.
*
* @param string $index
* @param string $type
* @return ProviderInterface
* @throws InvalidArgumentException if no provider was registered for the index and type
*/
public function getProvider($index, $type)
{
if (!isset($this->providers[$index][$type])) {
throw new \InvalidArgumentException(sprintf('No provider was registered for index "%s" and type "%s".', $index, $type));
}
return $this->container->get($this->providers[$index][$type]);
}
/**
* @see Symfony\Component\DependencyInjection\ContainerAwareInterface::setContainer()
*/
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
}