Passed
Push — master ( 8d0c4c...696880 )
by WEBEWEB
12:32 queued 09:29
created

DataTablesController::showAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
eloc 4
dl 0
loc 8
rs 10
c 2
b 0
f 1
cc 1
nc 1
nop 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\ORM\EntityNotFoundException;
16
use Symfony\Component\HttpFoundation\JsonResponse;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\HttpFoundation\Response;
19
use Symfony\Component\HttpFoundation\StreamedResponse;
20
use Throwable;
21
use WBW\Bundle\JQuery\DataTablesBundle\Event\DataTablesEvent;
22
use WBW\Bundle\JQuery\DataTablesBundle\Exception\BadDataTablesColumnException;
23
use WBW\Bundle\JQuery\DataTablesBundle\Exception\BadDataTablesCSVExporterException;
24
use WBW\Bundle\JQuery\DataTablesBundle\Exception\BadDataTablesEditorException;
25
use WBW\Bundle\JQuery\DataTablesBundle\Exception\BadDataTablesRepositoryException;
26
use WBW\Bundle\JQuery\DataTablesBundle\Exception\UnregisteredDataTablesProviderException;
27
use WBW\Bundle\JQuery\DataTablesBundle\Factory\DataTablesFactory;
28
use WBW\Bundle\JQuery\DataTablesBundle\Helper\DataTablesEntityHelper;
29
use WBW\Bundle\JQuery\DataTablesBundle\Helper\DataTablesExportHelper;
30
use WBW\Bundle\JQuery\DataTablesBundle\Helper\DataTablesWrapperHelper;
31
use WBW\Bundle\JQuery\DataTablesBundle\Model\DataTablesEnumerator;
32
use WBW\Bundle\JQuery\DataTablesBundle\Model\DataTablesLoop;
33
use WBW\Library\Types\Helper\BooleanHelper;
34
35
/**
36
 * DataTables controller.
37
 *
38
 * @author webeweb <https://github.com/webeweb>
39
 * @package WBW\Bundle\JQuery\DataTablesBundle\Controller
40
 */
41
class DataTablesController extends AbstractController {
42
43
    /**
44
     * Service name.
45
     *
46
     * @var string
47
     */
48
    const SERVICE_NAME = "wbw.jquery.datatables.controller.datatables";
49
50
    /**
51
     * Delete an existing entity.
52
     *
53
     * @param Request $request The request.
54
     * @param string $name The provider name.
55
     * @param string $id The entity id.
56
     * @return Response Returns the response.
57
     * @throws Throwable Throws an exception if an error occurs.
58
     * @throws UnregisteredDataTablesProviderException Throws an unregistered provider exception.
59
     */
60
    public function deleteAction(Request $request, string $name, string $id): Response {
61
62
        $dtProvider = $this->getDataTablesProvider($name);
63
64
        try {
65
66
            $entity = $this->getDataTablesEntityById($dtProvider, $id);
67
68
            $this->dispatchDataTablesEvent(DataTablesEvent::PRE_DELETE, [$entity], $dtProvider);
69
70
            $em = $this->getEntityManager();
71
            $em->remove($entity);
72
            $em->flush();
73
74
            $this->dispatchDataTablesEvent(DataTablesEvent::POST_DELETE, [$entity], $dtProvider);
75
76
            $output = $this->prepareActionResponse(200, "controller.datatables.delete.success");
77
        } catch (Throwable $ex) {
78
79
            $output = $this->handleDataTablesException($ex, "controller.datatables.delete");
80
        }
81
82
        return $this->buildDataTablesResponse($request, $name, $output);
83
    }
84
85
    /**
86
     * Edit an existing entity.
87
     *
88
     * @param Request $request The request.
89
     * @param string $name The provider name
90
     * @param string $id The entity id.
91
     * @param string $data The data.
92
     * @param mixed $value The value
93
     * @return Response Returns the response.
94
     * @throws UnregisteredDataTablesProviderException Throws an unregistered provider exception.
95
     * @throws BadDataTablesEditorException Throws a bad editor exception.
96
     * @throws BadDataTablesColumnException Throws a bad column exception.
97
     * @throws Throwable Throws an exception if an error occurs.
98
     */
99
    public function editAction(Request $request, string $name, string $id, string $data, $value): Response {
100
101
        $dtProvider = $this->getDataTablesProvider($name);
102
        $dtEditor   = $this->getDataTablesEditor($dtProvider);
103
        $dtColumn   = $this->getDataTablesColumn($dtProvider, $data);
104
105
        try {
106
107
            $entity = $this->getDataTablesEntityById($dtProvider, $id);
108
109
            if (true === $request->isMethod("POST")) {
110
                $value = $request->request->get("value");
111
            }
112
113
            $this->dispatchDataTablesEvent(DataTablesEvent::PRE_EDIT, [$entity], $dtProvider);
114
115
            $dtEditor->editColumn($dtColumn, $entity, $value);
116
117
            $em = $this->getEntityManager();
118
            $em->persist($entity);
119
            $em->flush();
120
121
            $this->dispatchDataTablesEvent(DataTablesEvent::POST_EDIT, [$entity], $dtProvider);
122
123
            $output = $this->prepareActionResponse(200, "controller.datatables.edit.success");
124
        } catch (Throwable $ex) {
125
126
            $output = $this->handleDataTablesException($ex, "controller.datatables.edit");
127
        }
128
129
        return new JsonResponse($output);
130
    }
131
132
    /**
133
     * Export all entities.
134
     *
135
     * @param Request $request The request.
136
     * @param string $name The provider name.
137
     * @return Response Returns the response.
138
     * @throws UnregisteredDataTablesProviderException Throws an unregistered provider exception.
139
     * @throws BadDataTablesCSVExporterException Throws a bad CSV exporter exception.
140
     * @throws BadDataTablesRepositoryException Throws a bad repository exception.
141
     * @throws Throwable Throws an exception if an error occurs.
142
     */
143
    public function exportAction(Request $request, string $name): Response {
144
145
        $windows = DataTablesExportHelper::isWindows($request);
146
147
        $dtProvider = $this->getDataTablesProvider($name);
148
        $dtExporter = $this->getDataTablesCSVExporter($dtProvider);
149
        $repository = $this->getDataTablesRepository($dtProvider);
150
151
        $dtWrapper = $this->getDataTablesWrapper($dtProvider);
152
        DataTablesFactory::parseWrapper($dtWrapper, $request);
153
154
        $filename = (new DateTime())->format("Y.m.d-H.i.s") . "-" . $dtProvider->getName() . ".csv";
155
        $charset  = true === $windows ? "iso-8859-1" : "utf-8";
156
157
        $response = new StreamedResponse();
158
        $response->headers->set("Content-Disposition", 'attachment; filename="' . $filename . '"');
159
        $response->headers->set("Content-Type", "text/csv; charset=" . $charset);
160
        $response->setCallback(function() use ($dtWrapper, $repository, $dtExporter, $windows) {
161
            $this->exportDataTablesCallback($dtWrapper, $repository, $dtExporter, $windows);
162
        });
163
        $response->setStatusCode(200);
164
165
        return $response;
166
    }
167
168
    /**
169
     * List all entities.
170
     *
171
     * @param Request $request The request.
172
     * @param string $name The provider name.
173
     * @return Response Returns the response.
174
     * @throws BadDataTablesRepositoryException Throws a bad repository exception.
175
     * @throws UnregisteredDataTablesProviderException Throws an unregistered provider exception.
176
     * @throws Throwable Throws an exception if an error occurs.
177
     */
178
    public function indexAction(Request $request, string $name): Response {
179
180
        if (false === $request->isXmlHttpRequest()) {
181
            return $this->renderAction($name);
182
        }
183
184
        $dtProvider = $this->getDataTablesProvider($name);
185
        $repository = $this->getDataTablesRepository($dtProvider);
186
187
        $dtWrapper = $this->getDataTablesWrapper($dtProvider);
188
        DataTablesFactory::parseWrapper($dtWrapper, $request);
189
190
        $dtRecords = $repository->dataTablesCountTotal($dtWrapper);
191
192
        $dtWrapper->getResponse()->setRecordsTotal($dtRecords);
193
        $dtWrapper->getResponse()->setRecordsFiltered($dtRecords);
194
195
        if (true === DataTablesWrapperHelper::hasSearch($dtWrapper)) {
196
            $dtWrapper->getResponse()->setRecordsFiltered($repository->dataTablesCountFiltered($dtWrapper));
197
        }
198
199
        $entities = $repository->dataTablesFindAll($dtWrapper);
200
201
        $this->dispatchDataTablesEvent(DataTablesEvent::PRE_INDEX, $entities, $dtProvider);
202
203
        $dtLoop = new DataTablesLoop($entities);
204
205
        foreach ($entities as $entity) {
206
207
            $dtWrapper->getResponse()->addRow();
208
209
            // Render each row.
210
            foreach (DataTablesEnumerator::enumRows() as $dtRow) {
211
                $dtWrapper->getResponse()->setRow($dtRow, $dtProvider->renderRow($dtRow, $entity, $dtLoop->getIndex0()));
212
            }
213
214
            // Render each column.
215
            foreach ($dtWrapper->getColumns() as $dtColumn) {
216
                $dtWrapper->getResponse()->setRow($dtColumn->getData(), $dtProvider->renderColumn($dtColumn, $entity));
0 ignored issues
show
Bug introduced by
It seems like $dtColumn->getData() can also be of type null; however, parameter $data of WBW\Bundle\JQuery\DataTa...onseInterface::setRow() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

216
                $dtWrapper->getResponse()->setRow(/** @scrutinizer ignore-type */ $dtColumn->getData(), $dtProvider->renderColumn($dtColumn, $entity));
Loading history...
217
            }
218
219
            $dtLoop->next();
220
        }
221
222
        $this->dispatchDataTablesEvent(DataTablesEvent::POST_INDEX, $entities, $dtProvider);
223
224
        return new JsonResponse($dtWrapper->getResponse());
225
    }
226
227
    /**
228
     * Options of a DataTables.
229
     *
230
     * @param string $name The provider name.
231
     * @return Response Returns a response.
232
     * @throws Throwable Throws an exception if an error occurs.
233
     * @throws UnregisteredDataTablesProviderException Throws an unregistered provider exception.
234
     */
235
    public function optionsAction(string $name): Response {
236
237
        $dtProvider = $this->getDataTablesProvider($name);
238
        $dtWrapper  = $this->getDataTablesWrapper($dtProvider);
239
        $dtOptions  = DataTablesWrapperHelper::getOptions($dtWrapper);
240
241
        return new JsonResponse($dtOptions);
242
    }
243
244
    /**
245
     * Render a DataTables.
246
     *
247
     * @param string $name The provider name.
248
     * @param string|null $alone Alone ?
249
     * @return Response Returns the response.
250
     * @throws Throwable Throws an exception if an error occurs.
251
     * @throws UnregisteredDataTablesProviderException Throws an unregistered provider exception.
252
     */
253
    public function renderAction(string $name, string $alone = null): Response {
254
255
        $dtProvider = $this->getDataTablesProvider($name);
256
        $dtWrapper  = $this->getDataTablesWrapper($dtProvider);
257
258
        $dtView = $dtProvider->getView();
259
        if (null === $dtProvider->getView()) {
260
            $dtView = "@WBWJQueryDataTables/datatables/index.html.twig";
261
        }
262
        if (true === BooleanHelper::parseString($alone)) {
263
            $dtView = "@WBWJQueryDataTables/datatables/render.html.twig";
264
        }
265
266
        return $this->render($dtView, [
0 ignored issues
show
Bug introduced by
It seems like $dtView can also be of type null; however, parameter $view of Symfony\Bundle\Framework...actController::render() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

266
        return $this->render(/** @scrutinizer ignore-type */ $dtView, [
Loading history...
267
            "dtWrapper" => $dtWrapper,
268
        ]);
269
    }
270
271
    /**
272
     * Serialize an existing entity.
273
     *
274
     * @param string $name The provider name.
275
     * @param string $id The entity id.
276
     * @return Response Returns the response.
277
     * @throws BadDataTablesRepositoryException Throws a bad repository exception.
278
     * @throws Throwable Throws an exception if an error occurs.
279
     * @throws UnregisteredDataTablesProviderException Throws an unregistered provider exception.
280
     */
281
    public function serializeAction(string $name, string $id): Response {
282
283
        $dtProvider = $this->getDataTablesProvider($name);
284
285
        $entity = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $entity is dead and can be removed.
Loading history...
286
287
        try {
288
289
            $entity = $this->getDataTablesEntityById($dtProvider, $id);
290
291
            $this->dispatchDataTablesEvent(DataTablesEvent::PRE_SERIALIZE, [$entity], $dtProvider);
292
        } catch (EntityNotFoundException $ex) {
293
            $this->logInfo($ex->getMessage());
294
        }
295
296
        $data = DataTablesEntityHelper::jsonSerialize($entity);
297
298
        return new Response($data, 200, ["Content-type" => "application/json"]);
299
    }
300
}
301