ModelFilter.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. if (!$this->getOption('field_name')) {
  49. throw new \RunTimeException('please provide a field_name options');
  50. }
  51. $queryBuilder->leftJoin(sprintf('%s.%s', $queryBuilder->getRootAlias(), $this->getOption('field_name')), $this->getName());
  52. return array($this->getOption('field_name'), 'id');
  53. }
  54. public function getDefaultOptions()
  55. {
  56. return array(
  57. 'mapping_type' => false,
  58. 'field_name' => false
  59. );
  60. }
  61. }