SearchHandler.php 1.7 KB

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