Completed
Push — 3.x ( 3e834f...38b337 )
by Grégoire
03:36
created

src/Action/SearchAction.php (1 issue)

Labels
Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Sonata Project package.
7
 *
8
 * (c) Thomas Rabaix <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Sonata\AdminBundle\Action;
15
16
use Sonata\AdminBundle\Admin\AdminInterface;
17
use Sonata\AdminBundle\Admin\BreadcrumbsBuilderInterface;
18
use Sonata\AdminBundle\Admin\Pool;
19
use Sonata\AdminBundle\Search\SearchHandler;
20
use Sonata\AdminBundle\Templating\TemplateRegistryInterface;
21
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
22
use Symfony\Component\HttpFoundation\JsonResponse;
23
use Symfony\Component\HttpFoundation\Request;
24
use Symfony\Component\HttpFoundation\Response;
25
use Twig\Environment;
26
27
final class SearchAction
28
{
29
    /**
30
     * @var Pool
31
     */
32
    private $pool;
33
34
    /**
35
     * @var SearchHandler
36
     */
37
    private $searchHandler;
38
39
    /**
40
     * @var TemplateRegistryInterface
41
     */
42
    private $templateRegistry;
43
44
    /**
45
     * @var BreadcrumbsBuilderInterface
46
     */
47
    private $breadcrumbsBuilder;
48
49
    /**
50
     * @var Environment
51
     */
52
    private $twig;
53
54
    public function __construct(
55
        Pool $pool,
56
        SearchHandler $searchHandler,
57
        TemplateRegistryInterface $templateRegistry,
58
        BreadcrumbsBuilderInterface $breadcrumbsBuilder,
59
        Environment $twig
60
    ) {
61
        $this->pool = $pool;
62
        $this->searchHandler = $searchHandler;
63
        $this->templateRegistry = $templateRegistry;
64
        $this->breadcrumbsBuilder = $breadcrumbsBuilder;
65
        $this->twig = $twig;
66
    }
67
68
    /**
69
     * The search action first render an empty page, if the query is set, then the template generates
70
     * some ajax request to retrieve results for each admin. The Ajax query returns a JSON response.
71
     *
72
     * @return JsonResponse|Response
73
     */
74
    public function __invoke(Request $request): Response
75
    {
76
        if (!$request->get('admin') || !$request->isXmlHttpRequest()) {
77
            return new Response($this->twig->render($this->templateRegistry->getTemplate('search'), [
78
                'base_template' => $request->isXmlHttpRequest() ?
79
                    $this->templateRegistry->getTemplate('ajax') :
80
                    $this->templateRegistry->getTemplate('layout'),
81
                'breadcrumbs_builder' => $this->breadcrumbsBuilder,
82
                'admin_pool' => $this->pool,
83
                'query' => $request->get('q'),
84
                'groups' => $this->pool->getDashboardGroups(),
85
            ]));
86
        }
87
88
        try {
89
            $admin = $this->pool->getAdminByAdminCode($request->get('admin'));
90
        } catch (ServiceNotFoundException $e) {
91
            throw new \RuntimeException('Unable to find the Admin instance', $e->getCode(), $e);
92
        }
93
94
        if (!$admin instanceof AdminInterface) {
95
            throw new \RuntimeException('The requested service is not an Admin instance');
96
        }
97
98
        $results = [];
99
100
        $page = false;
101
        $total = false;
102
        if ($pager = $this->searchHandler->search(
103
            $admin,
104
            $request->get('q'),
105
            $request->get('page'),
106
            $request->get('offset')
107
        )) {
108
            foreach ($pager->getResults() as $result) {
109
                $results[] = [
110
                    'label' => $admin->toString($result),
111
                    'link' => $admin->getSearchResultLink($result),
112
                    'id' => $admin->id($result),
113
                ];
114
            }
115
            $page = (int) $pager->getPage();
116
            $total = (int) $pager->getNbResults();
0 ignored issues
show
The method getNbResults() does not exist on Sonata\AdminBundle\Datagrid\PagerInterface. Did you maybe mean getResults()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
117
        }
118
119
        $response = new JsonResponse([
120
            'results' => $results,
121
            'page' => $page,
122
            'total' => $total,
123
        ]);
124
        $response->setPrivate();
125
126
        return $response;
127
    }
128
}
129