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