SearchHandler.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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\Search;
  11. use Sonata\AdminBundle\Admin\AdminInterface;
  12. use Sonata\AdminBundle\Admin\Pool;
  13. use Sonata\AdminBundle\Filter\FilterInterface;
  14. /**
  15. * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
  16. */
  17. class SearchHandler
  18. {
  19. protected $pool;
  20. /**
  21. * @param Pool $pool
  22. */
  23. public function __construct(Pool $pool)
  24. {
  25. $this->pool = $pool;
  26. }
  27. /**
  28. * @param AdminInterface $admin
  29. * @param string $term
  30. * @param int $page
  31. * @param int $offset
  32. *
  33. * @return \Sonata\AdminBundle\Datagrid\PagerInterface
  34. *
  35. * @throws \RuntimeException
  36. */
  37. public function search(AdminInterface $admin, $term, $page = 0, $offset = 20)
  38. {
  39. $datagrid = $admin->getDatagrid();
  40. $found = false;
  41. foreach ($datagrid->getFilters() as $name => $filter) {
  42. /** @var $filter FilterInterface */
  43. if ($filter->getOption('global_search', false)) {
  44. $filter->setCondition(FilterInterface::CONDITION_OR);
  45. $datagrid->setValue($name, null, $term);
  46. $found = true;
  47. }
  48. }
  49. if (!$found) {
  50. return false;
  51. }
  52. $datagrid->buildPager();
  53. $pager = $datagrid->getPager();
  54. $pager->setPage($page);
  55. $pager->setMaxPerPage($offset);
  56. return $pager;
  57. }
  58. }