Completed
Push — 3.x ( 799626...732596 )
by Grégoire
04:11
created

CoreController::dashboardAction()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 16
nc 4
nop 0
1
<?php
2
3
/*
4
 * This file is part of the Sonata Project package.
5
 *
6
 * (c) Thomas Rabaix <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sonata\AdminBundle\Controller;
13
14
use Sonata\AdminBundle\Admin\AdminInterface;
15
use Sonata\AdminBundle\Admin\Pool;
16
use Sonata\AdminBundle\Search\SearchHandler;
17
use Sonata\AdminBundle\Templating\TemplateRegistryInterface;
18
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
19
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
20
use Symfony\Component\HttpFoundation\JsonResponse;
21
use Symfony\Component\HttpFoundation\Request;
22
use Symfony\Component\HttpFoundation\Response;
23
24
/**
25
 * @author Thomas Rabaix <[email protected]>
26
 */
27
class CoreController extends Controller
28
{
29
    /**
30
     * @return Response
31
     */
32
    public function dashboardAction()
33
    {
34
        $blocks = [
35
            'top' => [],
36
            'left' => [],
37
            'center' => [],
38
            'right' => [],
39
            'bottom' => [],
40
        ];
41
42
        foreach ($this->container->getParameter('sonata.admin.configuration.dashboard_blocks') as $block) {
43
            $blocks[$block['position']][] = $block;
44
        }
45
46
        $parameters = [
47
            'base_template' => $this->getBaseTemplate(),
48
            'admin_pool' => $this->container->get('sonata.admin.pool'),
49
            'blocks' => $blocks,
50
        ];
51
52
        if (!$this->getCurrentRequest()->isXmlHttpRequest()) {
53
            $parameters['breadcrumbs_builder'] = $this->get('sonata.admin.breadcrumbs_builder');
54
        }
55
56
        return $this->render($this->getTemplateRegistry()->getTemplate('dashboard'), $parameters);
57
    }
58
59
    /**
60
     * The search action first render an empty page, if the query is set, then the template generates
61
     * some ajax request to retrieve results for each admin. The Ajax query returns a JSON response.
62
     *
63
     * @throws \RuntimeException
64
     *
65
     * @return JsonResponse|Response
66
     */
67
    public function searchAction(Request $request)
68
    {
69
        if ($request->get('admin') && $request->isXmlHttpRequest()) {
70
            try {
71
                $admin = $this->getAdminPool()->getAdminByAdminCode($request->get('admin'));
72
            } catch (ServiceNotFoundException $e) {
73
                throw new \RuntimeException('Unable to find the Admin instance', $e->getCode(), $e);
74
            }
75
76
            if (!$admin instanceof AdminInterface) {
77
                throw new \RuntimeException('The requested service is not an Admin instance');
78
            }
79
80
            $handler = $this->getSearchHandler();
81
82
            $results = [];
83
84
            if ($pager = $handler->search($admin, $request->get('q'), $request->get('page'), $request->get('offset'))) {
85
                foreach ($pager->getResults() as $result) {
86
                    $results[] = [
87
                        'label' => $admin->toString($result),
88
                        'link' => $admin->generateObjectUrl('edit', $result),
89
                        'id' => $admin->id($result),
90
                    ];
91
                }
92
            }
93
94
            $response = new JsonResponse([
95
                'results' => $results,
96
                'page' => $pager ? (int) $pager->getPage() : false,
97
                'total' => $pager ? (int) $pager->getNbResults() : false,
0 ignored issues
show
Bug introduced by
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...
98
            ]);
99
            $response->setPrivate();
100
101
            return $response;
102
        }
103
104
        return $this->render($this->getTemplateRegistry()->getTemplate('search'), [
105
            'base_template' => $this->getBaseTemplate(),
106
            'breadcrumbs_builder' => $this->get('sonata.admin.breadcrumbs_builder'),
107
            'admin_pool' => $this->container->get('sonata.admin.pool'),
108
            'query' => $request->get('q'),
109
            'groups' => $this->getAdminPool()->getDashboardGroups(),
110
        ]);
111
    }
112
113
    /**
114
     * Get the request object from the container.
115
     *
116
     * This method is compatible with both Symfony 2.3 and Symfony 3
117
     *
118
     * NEXT_MAJOR: remove this method.
119
     *
120
     * @deprecated since 3.0, to be removed in 4.0 and action methods will be adjusted.
121
     *             Use Symfony\Component\HttpFoundation\Request as an action argument
122
     *
123
     * @return Request
124
     */
125
    public function getRequest()
126
    {
127
        @trigger_error(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
128
            'The '.__METHOD__.' method is deprecated since 3.0 and will be removed in 4.0.'.
129
            ' Inject the Symfony\Component\HttpFoundation\Request into the actions instead.',
130
            E_USER_DEPRECATED
131
        );
132
133
        return $this->getCurrentRequest();
134
    }
135
136
    /**
137
     * @return Pool
138
     */
139
    protected function getAdminPool()
140
    {
141
        return $this->container->get('sonata.admin.pool');
142
    }
143
144
    /**
145
     * @return SearchHandler
146
     */
147
    protected function getSearchHandler()
148
    {
149
        return $this->get('sonata.admin.search.handler');
150
    }
151
152
    /**
153
     * @return string
154
     */
155
    protected function getBaseTemplate()
156
    {
157
        if ($this->getCurrentRequest()->isXmlHttpRequest()) {
158
            return $this->getTemplateRegistry()->getTemplate('ajax');
159
        }
160
161
        return $this->getTemplateRegistry()->getTemplate('layout');
162
    }
163
164
    /**
165
     * @return TemplateRegistryInterface
166
     */
167
    private function getTemplateRegistry()
168
    {
169
        return $this->container->get('sonata.admin.global_template_registry');
170
    }
171
172
    /**
173
     * Get the request object from the container.
174
     *
175
     * @return Request
176
     */
177
    private function getCurrentRequest()
178
    {
179
        return $this->container->get('request_stack')->getCurrentRequest();
180
    }
181
}
182