FilterFactory.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /*
  3. * This file is part of the Sonata Project 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. /**
  13. * Class FilterFactory.
  14. *
  15. * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
  16. */
  17. class FilterFactory implements FilterFactoryInterface
  18. {
  19. /**
  20. * @var ContainerInterface
  21. */
  22. protected $container;
  23. /**
  24. * @var string[]
  25. */
  26. protected $types;
  27. /**
  28. * @param ContainerInterface $container
  29. * @param string[] $types
  30. */
  31. public function __construct(ContainerInterface $container, array $types = array())
  32. {
  33. $this->container = $container;
  34. $this->types = $types;
  35. }
  36. /**
  37. * {@inheritdoc}
  38. */
  39. public function create($name, $type, array $options = array())
  40. {
  41. if (!$type) {
  42. throw new \RunTimeException('The type must be defined');
  43. }
  44. $id = isset($this->types[$type]) ? $this->types[$type] : false;
  45. if (!$id) {
  46. throw new \RunTimeException(sprintf('No attached service to type named `%s`', $type));
  47. }
  48. $filter = $this->container->get($id);
  49. if (!$filter instanceof FilterInterface) {
  50. throw new \RunTimeException(sprintf('The service `%s` must implement `FilterInterface`', $id));
  51. }
  52. $filter->initialize($name, $options);
  53. return $filter;
  54. }
  55. }