SearchHandler.php 1.7 KB

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