SearchHandler.php 1.7 KB

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