Completed
Push — master ( 20444a...763823 )
by WEBEWEB
02:46
created

DataTablesController::getDataTablesWrapper()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
1
<?php
2
3
/**
4
 * This file is part of the jquery-datatables-bundle package.
5
 *
6
 * (c) 2018 WEBEWEB
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 WBW\Bundle\JQuery\DataTablesBundle\Controller;
13
14
use Psr\Log\LoggerInterface;
15
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
16
use Symfony\Component\HttpFoundation\Request;
17
use Symfony\Component\HttpFoundation\Response;
18
use Symfony\Component\Routing\RouterInterface;
19
use WBW\Bundle\JQuery\DataTablesBundle\API\DataTablesResponse;
20
use WBW\Bundle\JQuery\DataTablesBundle\API\DataTablesWrapper;
21
use WBW\Bundle\JQuery\DataTablesBundle\Exception\BadDataTablesRepositoryException;
22
use WBW\Bundle\JQuery\DataTablesBundle\Exception\UnregisteredDataTablesProviderException;
23
use WBW\Bundle\JQuery\DataTablesBundle\Manager\DataTablesManager;
24
use WBW\Bundle\JQuery\DataTablesBundle\Provider\DataTablesProviderInterface;
25
use WBW\Bundle\JQuery\DataTablesBundle\Repository\DataTablesRepositoryInterface;
26
use WBW\Library\Core\IO\HTTPInterface;
27
28
/**
29
 * DataTables controller.
30
 *
31
 * @author webeweb <https://github.com/webeweb/>
32
 * @package WBW\Bundle\JQuery\DataTablesBundle\Controller
33
 */
34
class DataTablesController extends Controller {
35
36
    /**
37
     * Get the DataTables provider.
38
     *
39
     * @return DataTablesProviderInterface Returns the DataTables provider.
40
     */
41
    private function getDataTablesProvider($name) {
42
43
        // Log a debug trace.
44
        $this->getLogger()->debug(sprintf("DataTables controller search for a DataTables provider with name \"%s\"", $name));
45
46
        // Get the DataTables provider.
47
        $dtProvider = $this->get(DataTablesManager::SERVICE_NAME)->getProvider($name);
48
49
        // Log an info trace.
50
        $this->getLogger()->info(sprintf("DataTables controller found a DataTables provider with name \"%s\"", $name));
51
52
        // Return the DataTables provider.
53
        return $dtProvider;
54
    }
55
56
    /**
57
     * Get a DataTables wrapper.
58
     *
59
     * @param DataTablesProviderInterface $dtProvider The DataTables provider.
60
     * @return DataTablesWrapper Returns the DataTables wrapper.
61
     */
62
    private function getDataTablesWrapper(DataTablesProviderInterface $dtProvider) {
63
64
        // Initialize the DataTables wrapper.
65
        $dtWrapper = new DataTablesWrapper($dtProvider->getPrefix(), HTTPInterface::HTTP_METHOD_POST, $this->getRouter()->generate("jquery_datatables_index", ["name" => $dtProvider->getName()]));
66
67
        // Handle each column.
68
        foreach ($dtProvider->getColumns() as $dtColumn) {
69
70
            // Log a debug trace.
71
            $this->getLogger()->debug(sprintf("DataTables provider add a DataTables column \"%s\"", $dtColumn->getData()));
72
73
            // Add.
74
            $dtWrapper->addColumn($dtColumn);
75
        }
76
77
        // Return the DataTables wrapper.
78
        return $dtWrapper;
79
    }
80
81
    /**
82
     * Get the logger.
83
     *
84
     * @return LoggerInterface Returns the logger.
85
     */
86
    private function getLogger() {
87
        return $this->get("logger");
88
    }
89
90
    /**
91
     * Get the router.
92
     *
93
     * @return RouterInterface Returns the router.
94
     */
95
    private function getRouter() {
96
        return $this->get("router");
97
    }
98
99
    /**
100
     * Lists all entities.
101
     *
102
     * @param Request $request The request.
103
     * @param string $name The provider name.
104
     * @return Response Returns the response.
105
     * @throws UnregisteredDataTablesProviderException Throws an unregistered DataTables provider exception.
106
     * @throws BadDataTablesRepositoryException Throws a bad DataTables repository exception.
107
     */
108
    public function indexAction(Request $request, $name) {
109
110
        // Get the provider.
111
        $dtProvider = $this->getDataTablesProvider($name);
112
113
        // Get the wrapper.
114
        $dtWrapper = $this->getDataTablesWrapper($dtProvider);
115
116
        // Check if the request is an XML HTTP request.
117
        if (true === $request->isXmlHttpRequest()) {
118
119
            // Get the entities manager.
120
            $em = $this->getDoctrine()->getManager();
121
122
            // Get and check the entities repository.
123
            $repository = $em->getRepository($dtProvider->getEntity());
124
            if (false === ($repository instanceOf DataTablesRepositoryInterface)) {
125
                throw new BadDataTablesRepositoryException($repository);
126
            }
127
128
            // Parse the request.
129
            $dtWrapper->parse($request);
130
131
            //
132
            $filtered = $repository->dataTablesCountFiltered($dtWrapper);
133
            $total    = $repository->dataTablesCountTotal($dtWrapper);
134
            $entities = $repository->dataTablesFindAll($dtWrapper);
135
136
            // Set the response.
137
            $dtWrapper->getResponse()->setRecordsFiltered($filtered);
138
            $dtWrapper->getResponse()->setRecordsTotal($total);
139
140
            // Handle each entity.
141
            foreach ($entities as $entity) {
142
143
                // Count the rows.
144
                $rows = $dtWrapper->getResponse()->countRows();
145
146
                // Create a row.
147
                $dtWrapper->getResponse()->addRow();
148
149
                // Render each optional parameters.
150
                foreach (DataTablesResponse::dtRow() as $dtRow) {
151
                    $dtWrapper->getResponse()->setRow($dtRow, $dtProvider->renderRow($dtRow, $entity, $rows));
152
                }
153
154
                // Render each column.
155
                foreach ($dtWrapper->getColumns() as $dtColumn) {
156
                    $dtWrapper->getResponse()->setRow($dtColumn->getData(), $dtProvider->renderColumn($dtColumn, $entity));
157
                }
158
            }
159
160
            // Return the response.
161
            return new Response(json_encode($dtWrapper->getResponse()));
162
        }
163
164
        // Initialize the default view.
165
        $dtView = "@JQueryDataTables/DataTables/index.html.twig";
166
167
        // Check the provider view.
168
        if (null !== $dtProvider->getView()) {
169
            $dtView = $dtProvider->getView();
170
        }
171
172
        // Return the response.
173
        return $this->render($dtView, [
174
                "dtWrapper" => $dtWrapper,
175
        ]);
176
    }
177
178
}
179