Completed
Push — master ( e0d8bb...ebd563 )
by WEBEWEB
01:40
created

DataTablesController::exportAction()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 48
rs 9.1344
c 0
b 0
f 0
cc 2
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\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 Request $request The request.
91
     * @param string $name The provider name.
92
     * @return Response Returns the response.
93
     * @throws UnregisteredDataTablesProviderException Throws an unregistered DataTables provider exception.
94
     */
95
    public function exportAction(Request $request, $name) {
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
96
97
        // Get the provider.
98
        $dtProvider = $this->getDataTablesProvider($name);
99
100
        // Get the entities manager.
101
        $em = $this->getDoctrine()->getManager();
102
103
        // Get the entities repository.
104
        $repository = $this->getDataTablesRepository($dtProvider);
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->getDataTablesExportQuery($dtProvider)->getQuery()->iterate();
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 memomy 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
        // Get the provider.
156
        $dtProvider = $this->getDataTablesProvider($name);
157
158
        // Get the wrapper.
159
        $dtWrapper = $this->getDataTablesWrapper($dtProvider);
160
161
        // Check if the request is an XML HTTP request.
162
        if (false === $request->isXmlHttpRequest()) {
163
164
            // Get and check the provider view.
165
            $dtView = $dtProvider->getView();
166
            if (null === $dtProvider->getView()) {
167
                $dtView = "@JQueryDataTables/DataTables/index.html.twig";
168
            }
169
170
            // Return the response.
171
            return $this->render($dtView, [
172
                    "dtWrapper" => $dtWrapper,
173
            ]);
174
        }
175
176
        // Parse the request.
177
        $dtWrapper->parse($request);
178
179
        // Get the entities repository.
180
        $repository = $this->getDataTablesRepository($dtProvider);
181
182
        //
183
        $filtered = $repository->dataTablesCountFiltered($dtWrapper);
184
        $total    = $repository->dataTablesCountTotal($dtWrapper);
185
        $entities = $repository->dataTablesFindAll($dtWrapper);
186
187
        // Set the response.
188
        $dtWrapper->getResponse()->setRecordsFiltered($filtered);
189
        $dtWrapper->getResponse()->setRecordsTotal($total);
190
191
        // Handle each entity.
192
        foreach ($entities as $entity) {
193
194
            // Count the rows.
195
            $rows = $dtWrapper->getResponse()->countRows();
196
197
            // Create a row.
198
            $dtWrapper->getResponse()->addRow();
199
200
            // Render each optional parameter.
201
            foreach (DataTablesResponse::dtRow() as $dtRow) {
202
                $dtWrapper->getResponse()->setRow($dtRow, $dtProvider->renderRow($dtRow, $entity, $rows));
203
            }
204
205
            // Render each column.
206
            foreach ($dtWrapper->getColumns() as $dtColumn) {
207
                $dtWrapper->getResponse()->setRow($dtColumn->getData(), $dtProvider->renderColumn($dtColumn, $entity));
208
            }
209
        }
210
211
        // Return the response.
212
        return new Response(json_encode($dtWrapper->getResponse()));
213
    }
214
215
}
216