ModelFilter.php 1.9 KB

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