ModelFilter.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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\ORM;
  11. use Doctrine\ORM\QueryBuilder;
  12. use Doctrine\ORM\Mapping\ClassMetadataInfo;
  13. class ModelFilter extends Filter
  14. {
  15. /**
  16. * @param QueryBuilder $queryBuilder
  17. * @param string $alias
  18. * @param string $field
  19. * @param mixed $value
  20. * @return
  21. */
  22. public function filter($queryBuilder, $alias, $field, $value)
  23. {
  24. if (is_array($value)) {
  25. if (count($value) == 0) {
  26. return;
  27. }
  28. $queryBuilder->andWhere($queryBuilder->expr()->in(sprintf('%s.%s', $alias, $field ), $value));
  29. } else {
  30. if (empty($value)) {
  31. return;
  32. }
  33. $queryBuilder->andWhere(sprintf('%s.%s = :%s', $alias, $field, $this->getName()));
  34. $queryBuilder->setParameter($this->getName(), $value);
  35. }
  36. }
  37. protected function association($queryBuilder, $value)
  38. {
  39. $types = array(
  40. ClassMetadataInfo::ONE_TO_ONE,
  41. ClassMetadataInfo::ONE_TO_MANY,
  42. ClassMetadataInfo::MANY_TO_MANY,
  43. ClassMetadataInfo::MANY_TO_ONE,
  44. );
  45. if (!in_array($this->getOption('mapping_type'), $types)) {
  46. throw new \RunTimeException('Invalid mapping type');
  47. }
  48. $queryBuilder->leftJoin(sprintf('%s.%s', $queryBuilder->getRootAlias(), $this->getOption('field_name')), $this->getName());
  49. return array($this->getOption('field_name'), 'id');
  50. }
  51. public function getDefaultOptions()
  52. {
  53. return array(
  54. 'mapping_type' => false,
  55. 'field_name' => false
  56. );
  57. }
  58. }