Completed
Push — master ( b639a7...b026d2 )
by WEBEWEB
08:50
created

DataTablesController   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 223
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 20

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 20
dl 0
loc 223
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A deleteAction() 0 45 3
A exportAction() 0 48 2
B indexAction() 0 51 5
A optionsAction() 0 14 1
A renderAction() 0 19 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\Request;
18
use Symfony\Component\HttpFoundation\Response;
19
use Symfony\Component\HttpFoundation\StreamedResponse;
20
use WBW\Bundle\JQuery\DataTablesBundle\API\DataTablesResponse;
21
use WBW\Bundle\JQuery\DataTablesBundle\Exception\BadDataTablesRepositoryException;
22
use WBW\Bundle\JQuery\DataTablesBundle\Exception\UnregisteredDataTablesProviderException;
23
use WBW\Bundle\JQuery\DataTablesBundle\Helper\DataTablesHelper;
24
25
/**
26
 * DataTables controller.
27
 *
28
 * @author webeweb <https://github.com/webeweb/>
29
 * @package WBW\Bundle\JQuery\DataTablesBundle\Controller
30
 */
31
class DataTablesController extends AbstractDataTablesController {
32
33
    /**
34
     * Delete an existing entity.
35
     *
36
     * @param Request $request The request.
37
     * @param string $name The provider name.
38
     * @param string $id The entity id.
39
     * @throws UnregisteredDataTablesProviderException Throws an unregistered DataTables provider exception.
40
     * @throws BadDataTablesRepositoryException Throws a bad DataTables repository exception.
41
     */
42
    public function deleteAction(Request $request, $name, $id) {
43
44
        // Get the provider.
45
        $dtProvider = $this->getDataTablesProvider($name);
46
47
        // Initialize the output.
48
        $output = [
49
            "status" => null,
50
            "notify" => null,
51
        ];
52
53
        try {
54
55
            // Get the entity.
56
            $entity = $this->getDataTablesEntityById($dtProvider, $id);
57
58
            // Get the entities manager and delete the entity.
59
            $em = $this->getDoctrine()->getManager();
60
            $em->remove($entity);
61
            $em->flush();
62
63
            // Set the output.
64
            $output["status"] = 200;
65
            $output["notify"] = $this->getNotification("DataTablesController.deleteAction.success");
66
        } catch (EntityNotFoundException $ex) {
67
68
            // Log a debug trace.
69
            $this->getLogger()->debug($ex->getMessage());
70
71
            // Set the output.
72
            $output["status"] = 404;
73
            $output["notify"] = $this->getNotification("DataTablesController.deleteAction.danger");
74
        } catch (ForeignKeyConstraintViolationException $ex) {
75
76
            // Log a debug trace.
77
            $this->getLogger()->debug(sprintf("%s:%s %s", $ex->getErrorCode(), $ex->getSQLState(), $ex->getMessage()));
78
79
            // Set the output.
80
            $output["status"] = 500;
81
            $output["notify"] = $this->getNotification("DataTablesController.deleteAction.warning");
82
        }
83
84
        // Return the response.
85
        return $this->buildDataTablesResponse($request, $name, $output);
86
    }
87
88
    /**
89
     * Export all entities.
90
     *
91
     * @param string $name The provider name.
92
     * @return Response Returns the response.
93
     * @throws UnregisteredDataTablesProviderException Throws an unregistered DataTables provider exception.
94
     * @throws BadDataTablesRepositoryException Throws a bad DataTables repository exception.
95
     */
96
    public function exportAction($name) {
97
98
        // Get the provider.
99
        $dtProvider = $this->getDataTablesCSVExporter($name);
100
101
        // Get the entities repository.
102
        $repository = $this->getDataTablesRepository($dtProvider);
103
104
        // Get the entities manager.
105
        $em = $this->getDoctrine()->getManager();
106
107
        // Initialize the response.
108
        $response = new StreamedResponse(function() use($dtProvider, $repository, $em) {
109
110
            // Open the file.
111
            $stream = fopen("php://output", "w+");
112
113
            // Export the columns.
114
            fputcsv($stream, $dtProvider->exportColumns(), ";");
115
116
            // Get the export query.
117
            $result = $repository->dataTablesExportAll($dtProvider)->getQuery()->iterate();
0 ignored issues
show
Documentation introduced by
$dtProvider is of type object<WBW\Bundle\JQuery...esCSVExporterInterface>, but the function expects a object<WBW\Bundle\JQuery...ablesProviderInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
118
119
            // Handle each entity.
120
            while (false !== ($row = $result->next())) {
121
122
                // Export the entity.
123
                fputcsv($stream, $dtProvider->exportRow($row[0]), ";");
124
125
                // Detach the entity to avoid memory consumption.
126
                $em->detach($row[0]);
127
            }
128
129
            // Close the file.
130
            fclose($stream);
131
        });
132
133
        // Initialize the filename.
134
        $filename = (new DateTime())->format("Y.m.d-H.i.s") . "-" . $dtProvider->getName() . ".csv";
135
136
        // Set the response.
137
        $response->setStatusCode(200);
138
        $response->headers->set("Content-Disposition", "attachment; filename=\"" . $filename . "\"");
139
        $response->headers->set("Content-Type", "text/csv; charset=utf-8");
140
141
        // Return the response.
142
        return $response;
143
    }
144
145
    /**
146
     * Lists all entities.
147
     *
148
     * @param Request $request The request.
149
     * @param string $name The provider name.
150
     * @return Response Returns the response.
151
     * @throws UnregisteredDataTablesProviderException Throws an unregistered DataTables provider exception.
152
     * @throws BadDataTablesRepositoryException Throws a bad DataTables repository exception.
153
     */
154
    public function indexAction(Request $request, $name) {
155
156
        // Check if the request is an XML HTTP request.
157
        if (false === $request->isXmlHttpRequest()) {
158
            return $this->renderAction($name);
159
        }
160
161
        // Get the provider.
162
        $dtProvider = $this->getDataTablesProvider($name);
163
164
        // Get the wrapper.
165
        $dtWrapper = $this->getDataTablesWrapper($dtProvider);
166
167
        // Parse the request.
168
        $dtWrapper->parse($request);
169
170
        // Get the entities repository.
171
        $repository = $this->getDataTablesRepository($dtProvider);
172
173
        //
174
        $filtered = $repository->dataTablesCountFiltered($dtWrapper);
175
        $total    = $repository->dataTablesCountTotal($dtWrapper);
176
        $entities = $repository->dataTablesFindAll($dtWrapper);
177
178
        // Set the response.
179
        $dtWrapper->getResponse()->setRecordsFiltered($filtered);
180
        $dtWrapper->getResponse()->setRecordsTotal($total);
181
182
        // Handle each entity.
183
        foreach ($entities as $entity) {
184
185
            // Count the rows.
186
            $rows = $dtWrapper->getResponse()->countRows();
187
188
            // Create a row.
189
            $dtWrapper->getResponse()->addRow();
190
191
            // Render each optional parameter.
192
            foreach (DataTablesResponse::dtRow() as $dtRow) {
193
                $dtWrapper->getResponse()->setRow($dtRow, $dtProvider->renderRow($dtRow, $entity, $rows));
194
            }
195
196
            // Render each column.
197
            foreach ($dtWrapper->getColumns() as $dtColumn) {
198
                $dtWrapper->getResponse()->setRow($dtColumn->getData(), $dtProvider->renderColumn($dtColumn, $entity));
199
            }
200
        }
201
202
        // Return the response.
203
        return new Response(json_encode($dtWrapper->getResponse()));
204
    }
205
206
    /**
207
     * Options of a DataTables.
208
     *
209
     * @param string $name The provider name.
210
     * @return Response Returns a response.
211
     */
212
    public function optionsAction($name) {
213
214
        // Get the provider.
215
        $dtProvider = $this->getDataTablesProvider($name);
216
217
        // Get the wrapper.
218
        $dtWrapper = $this->getDataTablesWrapper($dtProvider);
219
220
        // Get the options.
221
        $dtOptions = DataTablesHelper::getOptions($dtWrapper);
222
223
        // Return the response.
224
        return new Response(json_encode($dtOptions));
225
    }
226
227
    /**
228
     * Render a DataTables.
229
     *
230
     * @param string $name The provider name.
231
     * @return Response Returns the response.
232
     */
233
    public function renderAction($name) {
234
235
        // Get the provider.
236
        $dtProvider = $this->getDataTablesProvider($name);
237
238
        // Get the wrapper.
239
        $dtWrapper = $this->getDataTablesWrapper($dtProvider);
240
241
        // Get and check the provider view.
242
        $dtView = $dtProvider->getView();
243
        if (null === $dtProvider->getView()) {
244
            $dtView = "@JQueryDataTables/DataTables/index.html.twig";
245
        }
246
247
        // Return the response.
248
        return $this->render($dtView, [
249
                "dtWrapper" => $dtWrapper,
250
        ]);
251
    }
252
253
}
254