Completed
Push — master ( 6c943a...57ef02 )
by WEBEWEB
01:28
created

DataTablesController   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 236
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 17

Importance

Changes 0
Metric Value
wmc 14
lcom 1
cbo 17
dl 0
loc 236
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A deleteAction() 0 45 3
A exportAction() 0 26 1
B indexAction() 0 51 5
A optionsAction() 0 14 1
A renderAction() 0 19 2
A showAction() 0 24 2
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 DateTime;
15
use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
16
use Doctrine\ORM\EntityNotFoundException;
17
use Symfony\Component\HttpFoundation\JsonResponse;
18
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Component\HttpFoundation\Response;
20
use Symfony\Component\HttpFoundation\StreamedResponse;
21
use WBW\Bundle\JQuery\DataTablesBundle\API\DataTablesResponse;
22
use WBW\Bundle\JQuery\DataTablesBundle\Exception\BadDataTablesRepositoryException;
23
use WBW\Bundle\JQuery\DataTablesBundle\Exception\UnregisteredDataTablesProviderException;
24
use WBW\Bundle\JQuery\DataTablesBundle\Helper\DataTablesWrapperHelper;
25
26
/**
27
 * DataTables controller.
28
 *
29
 * @author webeweb <https://github.com/webeweb/>
30
 * @package WBW\Bundle\JQuery\DataTablesBundle\Controller
31
 */
32
class DataTablesController extends AbstractDataTablesController {
33
34
    /**
35
     * Delete an existing entity.
36
     *
37
     * @param Request $request The request.
38
     * @param string $name The provider name.
39
     * @param string $id The entity id.
40
     * @throws UnregisteredDataTablesProviderException Throws an unregistered provider exception.
41
     * @throws BadDataTablesRepositoryException Throws a bad repository exception.
42
     */
43
    public function deleteAction(Request $request, $name, $id) {
44
45
        // Get the provider.
46
        $dtProvider = $this->getDataTablesProvider($name);
47
48
        // Initialize the output.
49
        $output = [
50
            "status" => null,
51
            "notify" => null,
52
        ];
53
54
        try {
55
56
            // Get the entity.
57
            $entity = $this->getDataTablesEntityById($dtProvider, $id);
58
59
            // Get the entities manager and delete the entity.
60
            $em = $this->getDoctrine()->getManager();
61
            $em->remove($entity);
62
            $em->flush();
63
64
            // Set the output.
65
            $output["status"] = 200;
66
            $output["notify"] = $this->getNotification("DataTablesController.deleteAction.success");
67
        } catch (EntityNotFoundException $ex) {
68
69
            // Log a debug trace.
70
            $this->getLogger()->debug($ex->getMessage());
71
72
            // Set the output.
73
            $output["status"] = 404;
74
            $output["notify"] = $this->getNotification("DataTablesController.deleteAction.danger");
75
        } catch (ForeignKeyConstraintViolationException $ex) {
76
77
            // Log a debug trace.
78
            $this->getLogger()->debug(sprintf("%s:%s %s", $ex->getErrorCode(), $ex->getSQLState(), $ex->getMessage()));
79
80
            // Set the output.
81
            $output["status"] = 500;
82
            $output["notify"] = $this->getNotification("DataTablesController.deleteAction.warning");
83
        }
84
85
        // Return the response.
86
        return $this->buildDataTablesResponse($request, $name, $output);
87
    }
88
89
    /**
90
     * Export all entities.
91
     *
92
     * @param string $name The provider name.
93
     * @return Response Returns the response.
94
     * @throws UnregisteredDataTablesProviderException Throws an unregistered provider exception.
95
     * @throws BadDataTablesCSVExporterException Throws a bad CSV exporter exception.
96
     * @throws BadDataTablesRepositoryException Throws a bad repository exception.
97
     */
98
    public function exportAction($name) {
99
100
        // Get the provider.
101
        $dtProvider = $this->getDataTablesProvider($name);
102
103
        // Get the exporter.
104
        $dtExporter = $this->getDataTablesCSVExporter($dtProvider);
105
106
        // Get the entity repository.
107
        $repository = $this->getDataTablesRepository($dtProvider);
108
109
        // Initialize the filename.
110
        $filename = (new DateTime())->format("Y.m.d-H.i.s") . "-" . $dtProvider->getName() . ".csv";
111
112
        // Initialize the response.
113
        $response = new StreamedResponse();
114
        $response->headers->set("Content-Disposition", "attachment; filename=\"" . $filename . "\"");
115
        $response->headers->set("Content-Type", "text/csv; charset=utf-8");
116
        $response->setCallback(function() use($dtProvider, $repository, $dtExporter) {
117
            $this->exportCallback($dtProvider, $repository, $dtExporter);
118
        });
119
        $response->setStatusCode(200);
120
121
        // Return the response.
122
        return $response;
123
    }
124
125
    /**
126
     * Lists all entities.
127
     *
128
     * @param Request $request The request.
129
     * @param string $name The provider name.
130
     * @return Response Returns the response.
131
     * @throws UnregisteredDataTablesProviderException Throws an unregistered provider exception.
132
     * @throws BadDataTablesRepositoryException Throws a bad repository exception.
133
     */
134
    public function indexAction(Request $request, $name) {
135
136
        // Check if the request is an XML HTTP request.
137
        if (false === $request->isXmlHttpRequest()) {
138
            return $this->renderAction($name);
139
        }
140
141
        // Get the provider.
142
        $dtProvider = $this->getDataTablesProvider($name);
143
144
        // Get the wrapper.
145
        $dtWrapper = $this->getDataTablesWrapper($dtProvider);
146
147
        // Parse the request.
148
        $dtWrapper->parse($request);
149
150
        // Get the entities repository.
151
        $repository = $this->getDataTablesRepository($dtProvider);
152
153
        //
154
        $filtered = $repository->dataTablesCountFiltered($dtWrapper);
155
        $total    = $repository->dataTablesCountTotal($dtWrapper);
156
        $entities = $repository->dataTablesFindAll($dtWrapper);
157
158
        // Set the response.
159
        $dtWrapper->getResponse()->setRecordsFiltered($filtered);
160
        $dtWrapper->getResponse()->setRecordsTotal($total);
161
162
        // Handle each entity.
163
        foreach ($entities as $entity) {
164
165
            // Count the rows.
166
            $rows = $dtWrapper->getResponse()->countRows();
167
168
            // Create a row.
169
            $dtWrapper->getResponse()->addRow();
170
171
            // Render each row.
172
            foreach (DataTablesResponse::dtRows() as $dtRow) {
173
                $dtWrapper->getResponse()->setRow($dtRow, $dtProvider->renderRow($dtRow, $entity, $rows));
174
            }
175
176
            // Render each column.
177
            foreach ($dtWrapper->getColumns() as $dtColumn) {
178
                $dtWrapper->getResponse()->setRow($dtColumn->getData(), $dtProvider->renderColumn($dtColumn, $entity));
179
            }
180
        }
181
182
        // Return the response.
183
        return new JsonResponse($dtWrapper->getResponse());
184
    }
185
186
    /**
187
     * Options of a DataTables.
188
     *
189
     * @param string $name The provider name.
190
     * @return Response Returns a response.
191
     * @throws UnregisteredDataTablesProviderException Throws an unregistered provider exception.
192
     */
193
    public function optionsAction($name) {
194
195
        // Get the provider.
196
        $dtProvider = $this->getDataTablesProvider($name);
197
198
        // Get the wrapper.
199
        $dtWrapper = $this->getDataTablesWrapper($dtProvider);
200
201
        // Get the options.
202
        $dtOptions = DataTablesWrapperHelper::getOptions($dtWrapper);
203
204
        // Return the response.
205
        return new JsonResponse($dtOptions);
206
    }
207
208
    /**
209
     * Render a DataTables.
210
     *
211
     * @param string $name The provider name.
212
     * @return Response Returns the response.
213
     * @throws UnregisteredDataTablesProviderException Throws an unregistered provider exception.
214
     */
215
    public function renderAction($name) {
216
217
        // Get the provider.
218
        $dtProvider = $this->getDataTablesProvider($name);
219
220
        // Get the wrapper.
221
        $dtWrapper = $this->getDataTablesWrapper($dtProvider);
222
223
        // Get and check the provider view.
224
        $dtView = $dtProvider->getView();
225
        if (null === $dtProvider->getView()) {
226
            $dtView = "@JQueryDataTables/DataTables/index.html.twig";
227
        }
228
229
        // Return the response.
230
        return $this->render($dtView, [
231
                "dtWrapper" => $dtWrapper,
232
        ]);
233
    }
234
235
    /**
236
     * Show an existing entity.
237
     *
238
     * @param string $name The provider name.
239
     * @param string $id The entity id.
240
     * @return Response Returns the response.
241
     */
242
    public function showAction($name, $id) {
243
244
        // Get the provider.
245
        $dtProvider = $this->getDataTablesProvider($name);
246
247
        try {
248
249
            // Get the entity.
250
            $entity = $this->getDataTablesEntityById($dtProvider, $id);
251
        } catch (EntityNotFoundException $ex) {
252
253
            // Log a debug trace.
254
            $this->getLogger()->debug($ex->getMessage());
255
256
            // Initialize the entity.
257
            $entity = [];
258
        }
259
260
        // Get the serializer.
261
        $serializer = $this->getDataTablesSerializer();
262
263
        // Return the response.
264
        return new Response($serializer->serialize($entity, "json"), 200, ["Content-type" => "application/json"]);
265
    }
266
267
}
268