FilterFactory.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /*
  3. * This file is part of the Sonata package.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Sonata\AdminBundle\Filter;
  11. use Symfony\Component\DependencyInjection\ContainerInterface;
  12. class FilterFactory implements FilterFactoryInterface
  13. {
  14. protected $container;
  15. protected $types;
  16. /**
  17. * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
  18. * @param array $types
  19. */
  20. public function __construct(ContainerInterface $container, array $types = array())
  21. {
  22. $this->container = $container;
  23. $this->types = $types;
  24. }
  25. /**
  26. * @throws \RunTimeException
  27. * @param string $name
  28. * @param string $type
  29. * @param array $options
  30. * @return \Sonata\AdminBundle\Filter\FilterInterface
  31. */
  32. public function create($name, $type, array $options = array())
  33. {
  34. if (!$type) {
  35. throw new \RunTimeException('The type must be defined');
  36. }
  37. $id = isset($this->types[$type]) ? $this->types[$type] : false;
  38. if (!$id) {
  39. throw new \RunTimeException(sprintf('No attached service to type named `%s`', $type));
  40. }
  41. $filter = $this->container->get($id);
  42. if (!$filter instanceof FilterInterface) {
  43. throw new \RunTimeException(sprintf('The service `%s` must implement `FilterInterface`', $id));
  44. }
  45. $filter->initialize($name, $options);
  46. return $filter;
  47. }
  48. }