Completed
Push — master ( e5e4cb...c0714e )
by WEBEWEB
01:31
created

DataTablesController::optionsAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0
cc 1
nc 1
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 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\BadDataTablesCSVExporterException;
23
use WBW\Bundle\JQuery\DataTablesBundle\Exception\BadDataTablesEditorException;
24
use WBW\Bundle\JQuery\DataTablesBundle\Exception\BadDataTablesRepositoryException;
25
use WBW\Bundle\JQuery\DataTablesBundle\Exception\UnregisteredDataTablesProviderException;
26
use WBW\Bundle\JQuery\DataTablesBundle\Helper\DataTablesWrapperHelper;
27
use WBW\Library\Core\Network\HTTP\HTTPInterface;
28
29
/**
30
 * DataTables controller.
31
 *
32
 * @author webeweb <https://github.com/webeweb/>
33
 * @package WBW\Bundle\JQuery\DataTablesBundle\Controller
34
 */
35
class DataTablesController extends AbstractDataTablesController {
36
37
    /**
38
     * Delete an existing entity.
39
     *
40
     * @param Request $request The request.
41
     * @param string $name The provider name.
42
     * @param string $id The entity id.
43
     * @throws UnregisteredDataTablesProviderException Throws an unregistered provider exception.
44
     * @throws BadDataTablesRepositoryException Throws a bad repository exception.
45
     */
46
    public function deleteAction(Request $request, $name, $id) {
47
48
        // Get the provider.
49
        $dtProvider = $this->getDataTablesProvider($name);
50
51
        try {
52
53
            // Get the entity.
54
            $entity = $this->getDataTablesEntityById($dtProvider, $id);
55
56
            // Get the entities manager and delete the entity.
57
            $em = $this->getDoctrine()->getManager();
58
            $em->remove($entity);
59
            $em->flush();
60
61
            // Set the output.
62
            $output = $this->prepareActionResponse(200, "DataTablesController.deleteAction.success");
63
        } catch (EntityNotFoundException $ex) {
64
65
            // Log a debug trace.
66
            $this->getLogger()->debug($ex->getMessage());
67
68
            // Set the output.
69
            $output = $this->prepareActionResponse(404, "DataTablesController.deleteAction.danger");
70
        } catch (ForeignKeyConstraintViolationException $ex) {
71
72
            // Log a debug trace.
73
            $this->getLogger()->debug(sprintf("%s:%s %s", $ex->getErrorCode(), $ex->getSQLState(), $ex->getMessage()));
74
75
            // Set the output.
76
            $output = $this->prepareActionResponse(500, "DataTablesController.deleteAction.warning");
77
        }
78
79
        // Return the response.
80
        return $this->buildDataTablesResponse($request, $name, $output);
81
    }
82
83
    /**
84
     * Edit an existing entity.
85
     *
86
     * @param Request $request The request.
87
     * @param string $name The provider name
88
     * @param string $id The entity id.
89
     * @param string $data The data.
90
     * @param mixed $value The value
91
     * @return Response Returns the response.
92
     * @throws UnregisteredDataTablesProviderException Throws an unregistered provider exception.
93
     * @throws BadDataTablesEditorException Throws a bad editor exception.
94
     */
95
    public function editAction(Request $request, $name, $id, $data, $value) {
96
97
        // Get the provider.
98
        $dtProvider = $this->getDataTablesProvider($name);
99
100
        // Get the editor.
101
        $dtEditor = $this->getDataTablesEditor($dtProvider);
102
103
        // Get the column.
104
        $dtColumn = $this->getDataTablesColumn($dtProvider, $data);
105
106
        try {
107
108
            // Get the entity.
109
            $entity = $this->getDataTablesEntityById($dtProvider, $id);
110
111
            // Set the value.
112
            if (true === $request->isMethod(HTTPInterface::HTTP_METHOD_POST)) {
113
                $value = $request->request->get("value");
114
            }
115
116
            // Set the entity.
117
            $dtEditor->editColumn($dtColumn, $entity, $value);
118
119
            // Get the entities manager and delete the entity.
120
            $em = $this->getDoctrine()->getManager();
121
            $em->persist($entity);
122
            $em->flush();
123
124
            // Set the output.
125
            $output = $this->prepareActionResponse(200, "DataTablesController.editAction.success");
126
        } catch (EntityNotFoundException $ex) {
127
128
            // Log a debug trace.
129
            $this->getLogger()->debug($ex->getMessage());
130
131
            // Set the output.
132
            $output = $this->prepareActionResponse(404, "DataTablesController.editAction.danger");
133
        } catch (ForeignKeyConstraintViolationException $ex) {
134
135
            // Log a debug trace.
136
            $this->getLogger()->debug(sprintf("%s:%s %s", $ex->getErrorCode(), $ex->getSQLState(), $ex->getMessage()));
137
138
            // Set the output.
139
            $output = $this->prepareActionResponse(500, "DataTablesController.editAction.warning");
140
        }
141
142
        // Return the response.
143
        return new JsonResponse($output);
144
    }
145
146
    /**
147
     * Export all entities.
148
     *
149
     * @param string $name The provider name.
150
     * @return Response Returns the response.
151
     * @throws UnregisteredDataTablesProviderException Throws an unregistered provider exception.
152
     * @throws BadDataTablesCSVExporterException Throws a bad CSV exporter exception.
153
     * @throws BadDataTablesRepositoryException Throws a bad repository exception.
154
     */
155
    public function exportAction($name) {
156
157
        // Get the provider.
158
        $dtProvider = $this->getDataTablesProvider($name);
159
160
        // Get the exporter.
161
        $dtExporter = $this->getDataTablesCSVExporter($dtProvider);
162
163
        // Get the entity repository.
164
        $repository = $this->getDataTablesRepository($dtProvider);
165
166
        // Initialize the filename.
167
        $filename = (new DateTime())->format("Y.m.d-H.i.s") . "-" . $dtProvider->getName() . ".csv";
168
169
        // Initialize the response.
170
        $response = new StreamedResponse();
171
        $response->headers->set("Content-Disposition", "attachment; filename=\"" . $filename . "\"");
172
        $response->headers->set("Content-Type", "text/csv; charset=utf-8");
173
        $response->setCallback(function() use($dtProvider, $repository, $dtExporter) {
174
            $this->exportCallback($dtProvider, $repository, $dtExporter);
175
        });
176
        $response->setStatusCode(200);
177
178
        // Return the response.
179
        return $response;
180
    }
181
182
    /**
183
     * Lists all entities.
184
     *
185
     * @param Request $request The request.
186
     * @param string $name The provider name.
187
     * @return Response Returns the response.
188
     * @throws UnregisteredDataTablesProviderException Throws an unregistered provider exception.
189
     * @throws BadDataTablesRepositoryException Throws a bad repository exception.
190
     */
191
    public function indexAction(Request $request, $name) {
192
193
        // Check if the request is an XML HTTP request.
194
        if (false === $request->isXmlHttpRequest()) {
195
            return $this->renderAction($name);
196
        }
197
198
        // Get the provider.
199
        $dtProvider = $this->getDataTablesProvider($name);
200
201
        // Get the wrapper.
202
        $dtWrapper = $this->getDataTablesWrapper($dtProvider);
203
204
        // Parse the request.
205
        $dtWrapper->parse($request);
206
207
        // Get the entities repository.
208
        $repository = $this->getDataTablesRepository($dtProvider);
209
210
        //
211
        $filtered = $repository->dataTablesCountFiltered($dtWrapper);
212
        $total    = $repository->dataTablesCountTotal($dtWrapper);
213
        $entities = $repository->dataTablesFindAll($dtWrapper);
214
215
        // Set the response.
216
        $dtWrapper->getResponse()->setRecordsFiltered($filtered);
217
        $dtWrapper->getResponse()->setRecordsTotal($total);
218
219
        // Handle each entity.
220
        foreach ($entities as $entity) {
221
222
            // Count the rows.
223
            $rows = $dtWrapper->getResponse()->countRows();
224
225
            // Create a row.
226
            $dtWrapper->getResponse()->addRow();
227
228
            // Render each row.
229
            foreach (DataTablesResponse::dtRows() as $dtRow) {
230
                $dtWrapper->getResponse()->setRow($dtRow, $dtProvider->renderRow($dtRow, $entity, $rows));
231
            }
232
233
            // Render each column.
234
            foreach ($dtWrapper->getColumns() as $dtColumn) {
235
                $dtWrapper->getResponse()->setRow($dtColumn->getData(), $dtProvider->renderColumn($dtColumn, $entity));
236
            }
237
        }
238
239
        // Return the response.
240
        return new JsonResponse($dtWrapper->getResponse());
241
    }
242
243
    /**
244
     * Options of a DataTables.
245
     *
246
     * @param string $name The provider name.
247
     * @return Response Returns a response.
248
     * @throws UnregisteredDataTablesProviderException Throws an unregistered provider exception.
249
     */
250
    public function optionsAction($name) {
251
252
        // Get the provider.
253
        $dtProvider = $this->getDataTablesProvider($name);
254
255
        // Get the wrapper.
256
        $dtWrapper = $this->getDataTablesWrapper($dtProvider);
257
258
        // Get the options.
259
        $dtOptions = DataTablesWrapperHelper::getOptions($dtWrapper);
260
261
        // Return the response.
262
        return new JsonResponse($dtOptions);
263
    }
264
265
    /**
266
     * Render a DataTables.
267
     *
268
     * @param string $name The provider name.
269
     * @return Response Returns the response.
270
     * @throws UnregisteredDataTablesProviderException Throws an unregistered provider exception.
271
     */
272
    public function renderAction($name) {
273
274
        // Get the provider.
275
        $dtProvider = $this->getDataTablesProvider($name);
276
277
        // Get the wrapper.
278
        $dtWrapper = $this->getDataTablesWrapper($dtProvider);
279
280
        // Get and check the provider view.
281
        $dtView = $dtProvider->getView();
282
        if (null === $dtProvider->getView()) {
283
            $dtView = "@JQueryDataTables/DataTables/index.html.twig";
284
        }
285
286
        // Return the response.
287
        return $this->render($dtView, [
288
                "dtWrapper" => $dtWrapper,
289
        ]);
290
    }
291
292
    /**
293
     * Show an existing entity.
294
     *
295
     * @param string $name The provider name.
296
     * @param string $id The entity id.
297
     * @return Response Returns the response.
298
     */
299
    public function showAction($name, $id) {
300
301
        // Get the provider.
302
        $dtProvider = $this->getDataTablesProvider($name);
303
304
        try {
305
306
            // Get the entity.
307
            $entity = $this->getDataTablesEntityById($dtProvider, $id);
308
        } catch (EntityNotFoundException $ex) {
309
310
            // Log a debug trace.
311
            $this->getLogger()->debug($ex->getMessage());
312
313
            // Initialize the entity.
314
            $entity = [];
315
        }
316
317
        // Get the serializer.
318
        $serializer = $this->getDataTablesSerializer();
319
320
        // Return the response.
321
        return new Response($serializer->serialize($entity, "json"), 200, ["Content-type" => "application/json"]);
322
    }
323
324
}
325