Completed
Push — master ( 02bf51...b639a7 )
by WEBEWEB
01:29
created

DataTablesController::renderAction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.6333
c 0
b 0
f 0
cc 2
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 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
24
/**
25
 * DataTables controller.
26
 *
27
 * @author webeweb <https://github.com/webeweb/>
28
 * @package WBW\Bundle\JQuery\DataTablesBundle\Controller
29
 */
30
class DataTablesController extends AbstractDataTablesController {
31
32
    /**
33
     * Delete an existing entity.
34
     *
35
     * @param Request $request The request.
36
     * @param string $name The provider name.
37
     * @param string $id The entity id.
38
     * @throws UnregisteredDataTablesProviderException Throws an unregistered DataTables provider exception.
39
     * @throws BadDataTablesRepositoryException Throws a bad DataTables repository exception.
40
     */
41
    public function deleteAction(Request $request, $name, $id) {
42
43
        // Get the provider.
44
        $dtProvider = $this->getDataTablesProvider($name);
45
46
        // Initialize the output.
47
        $output = [
48
            "status" => null,
49
            "notify" => null,
50
        ];
51
52
        try {
53
54
            // Get the entity.
55
            $entity = $this->getDataTablesEntityById($dtProvider, $id);
56
57
            // Get the entities manager and delete the entity.
58
            $em = $this->getDoctrine()->getManager();
59
            $em->remove($entity);
60
            $em->flush();
61
62
            // Set the output.
63
            $output["status"] = 200;
64
            $output["notify"] = $this->getNotification("DataTablesController.deleteAction.success");
65
        } catch (EntityNotFoundException $ex) {
66
67
            // Log a debug trace.
68
            $this->getLogger()->debug($ex->getMessage());
69
70
            // Set the output.
71
            $output["status"] = 404;
72
            $output["notify"] = $this->getNotification("DataTablesController.deleteAction.danger");
73
        } catch (ForeignKeyConstraintViolationException $ex) {
74
75
            // Log a debug trace.
76
            $this->getLogger()->debug(sprintf("%s:%s %s", $ex->getErrorCode(), $ex->getSQLState(), $ex->getMessage()));
77
78
            // Set the output.
79
            $output["status"] = 500;
80
            $output["notify"] = $this->getNotification("DataTablesController.deleteAction.warning");
81
        }
82
83
        // Return the response.
84
        return $this->buildDataTablesResponse($request, $name, $output);
85
    }
86
87
    /**
88
     * Export all entities.
89
     *
90
     * @param string $name The provider name.
91
     * @return Response Returns the response.
92
     * @throws UnregisteredDataTablesProviderException Throws an unregistered DataTables provider exception.
93
     * @throws BadDataTablesRepositoryException Throws a bad DataTables repository exception.
94
     */
95
    public function exportAction($name) {
96
97
        // Get the provider.
98
        $dtProvider = $this->getDataTablesCSVExporter($name);
99
100
        // Get the entities repository.
101
        $repository = $this->getDataTablesRepository($dtProvider);
102
103
        // Get the entities manager.
104
        $em = $this->getDoctrine()->getManager();
105
106
        // Initialize the response.
107
        $response = new StreamedResponse(function() use($dtProvider, $repository, $em) {
108
109
            // Open the file.
110
            $stream = fopen("php://output", "w+");
111
112
            // Export the columns.
113
            fputcsv($stream, $dtProvider->exportColumns(), ";");
114
115
            // Get the export query.
116
            $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...
117
118
            // Handle each entity.
119
            while (false !== ($row = $result->next())) {
120
121
                // Export the entity.
122
                fputcsv($stream, $dtProvider->exportRow($row[0]), ";");
123
124
                // Detach the entity to avoid memory consumption.
125
                $em->detach($row[0]);
126
            }
127
128
            // Close the file.
129
            fclose($stream);
130
        });
131
132
        // Initialize the filename.
133
        $filename = (new DateTime())->format("Y.m.d-H.i.s") . "-" . $dtProvider->getName() . ".csv";
134
135
        // Set the response.
136
        $response->setStatusCode(200);
137
        $response->headers->set("Content-Disposition", "attachment; filename=\"" . $filename . "\"");
138
        $response->headers->set("Content-Type", "text/csv; charset=utf-8");
139
140
        // Return the response.
141
        return $response;
142
    }
143
144
    /**
145
     * Lists all entities.
146
     *
147
     * @param Request $request The request.
148
     * @param string $name The provider name.
149
     * @return Response Returns the response.
150
     * @throws UnregisteredDataTablesProviderException Throws an unregistered DataTables provider exception.
151
     * @throws BadDataTablesRepositoryException Throws a bad DataTables repository exception.
152
     */
153
    public function indexAction(Request $request, $name) {
154
155
        // Check if the request is an XML HTTP request.
156
        if (false === $request->isXmlHttpRequest()) {
157
            return $this->renderAction($name);
158
        }
159
160
        // Get the provider.
161
        $dtProvider = $this->getDataTablesProvider($name);
162
163
        // Get the wrapper.
164
        $dtWrapper = $this->getDataTablesWrapper($dtProvider);
165
166
        // Parse the request.
167
        $dtWrapper->parse($request);
168
169
        // Get the entities repository.
170
        $repository = $this->getDataTablesRepository($dtProvider);
171
172
        //
173
        $filtered = $repository->dataTablesCountFiltered($dtWrapper);
174
        $total    = $repository->dataTablesCountTotal($dtWrapper);
175
        $entities = $repository->dataTablesFindAll($dtWrapper);
176
177
        // Set the response.
178
        $dtWrapper->getResponse()->setRecordsFiltered($filtered);
179
        $dtWrapper->getResponse()->setRecordsTotal($total);
180
181
        // Handle each entity.
182
        foreach ($entities as $entity) {
183
184
            // Count the rows.
185
            $rows = $dtWrapper->getResponse()->countRows();
186
187
            // Create a row.
188
            $dtWrapper->getResponse()->addRow();
189
190
            // Render each optional parameter.
191
            foreach (DataTablesResponse::dtRow() as $dtRow) {
192
                $dtWrapper->getResponse()->setRow($dtRow, $dtProvider->renderRow($dtRow, $entity, $rows));
193
            }
194
195
            // Render each column.
196
            foreach ($dtWrapper->getColumns() as $dtColumn) {
197
                $dtWrapper->getResponse()->setRow($dtColumn->getData(), $dtProvider->renderColumn($dtColumn, $entity));
198
            }
199
        }
200
201
        // Return the response.
202
        return new Response(json_encode($dtWrapper->getResponse()));
203
    }
204
205
    /**
206
     * Render a DataTables.
207
     *
208
     * @param string $name The provider name.
209
     * @return Response Returns the response.
210
     */
211
    public function renderAction($name) {
212
213
        // Get the provider.
214
        $dtProvider = $this->getDataTablesProvider($name);
215
216
        // Get the wrapper.
217
        $dtWrapper = $this->getDataTablesWrapper($dtProvider);
218
219
        // Get and check the provider view.
220
        $dtView = $dtProvider->getView();
221
        if (null === $dtProvider->getView()) {
222
            $dtView = "@JQueryDataTables/DataTables/index.html.twig";
223
        }
224
225
        // Return the response.
226
        return $this->render($dtView, [
227
                "dtWrapper" => $dtWrapper,
228
        ]);
229
    }
230
231
}
232