FilterFactory.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. *
  28. * @param string $name
  29. * @param string $type
  30. * @param array $options
  31. *
  32. * @return \Sonata\AdminBundle\Filter\FilterInterface
  33. */
  34. public function create($name, $type, array $options = array())
  35. {
  36. if (!$type) {
  37. throw new \RunTimeException('The type must be defined');
  38. }
  39. $id = isset($this->types[$type]) ? $this->types[$type] : false;
  40. if (!$id) {
  41. throw new \RunTimeException(sprintf('No attached service to type named `%s`', $type));
  42. }
  43. $filter = $this->container->get($id);
  44. if (!$filter instanceof FilterInterface) {
  45. throw new \RunTimeException(sprintf('The service `%s` must implement `FilterInterface`', $id));
  46. }
  47. $filter->initialize($name, $options);
  48. return $filter;
  49. }
  50. }