Completed
Push — master ( b026d2...e5ac1d )
by WEBEWEB
01:39
created

AbstractDataTablesController::exportCallback()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 41
rs 9.264
c 0
b 0
f 0
cc 3
nc 3
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 Doctrine\ORM\EntityNotFoundException;
15
use Doctrine\ORM\EntityRepository;
16
use Symfony\Component\HttpFoundation\Request;
17
use Symfony\Component\HttpFoundation\Response;
18
use WBW\Bundle\BootstrapBundle\Controller\AbstractBootstrapController;
19
use WBW\Bundle\JQuery\DataTablesBundle\API\DataTablesWrapper;
20
use WBW\Bundle\JQuery\DataTablesBundle\Exception\BadDataTablesCSVExporterException;
21
use WBW\Bundle\JQuery\DataTablesBundle\Exception\BadDataTablesRepositoryException;
22
use WBW\Bundle\JQuery\DataTablesBundle\Exception\UnregisteredDataTablesProviderException;
23
use WBW\Bundle\JQuery\DataTablesBundle\Manager\DataTablesManager;
24
use WBW\Bundle\JQuery\DataTablesBundle\Provider\DataTablesCSVExporterInterface;
25
use WBW\Bundle\JQuery\DataTablesBundle\Provider\DataTablesProviderInterface;
26
use WBW\Bundle\JQuery\DataTablesBundle\Repository\DataTablesRepositoryInterface;
27
use WBW\Library\Core\Utility\Argument\IntegerUtility;
28
29
/**
30
 * Abstract jQuery DataTables controller.
31
 *
32
 * @author webeweb <https://github.com/webeweb/>
33
 * @package WBW\Bundle\JQuery\DataTablesBundle\Controller
34
 * @abstract
35
 */
36
abstract class AbstractDataTablesController extends AbstractBootstrapController {
37
38
    /**
39
     * Build a DataTables response.
40
     *
41
     * @param Request $request The request.
42
     * @param string $name The provider name.
43
     * @param array $output The output.
44
     * @return Response Returns the DataTables response.
45
     */
46
    protected function buildDataTablesResponse(Request $request, $name, array $output) {
47
48
        // Determines if the request is an XML HTTP request.
49
        if (true === $request->isXmlHttpRequest()) {
50
51
            // Return the response.
52
            return new Response(json_encode($output));
53
        }
54
55
        // Notify the user.
56
        switch ($output["status"]) {
57
58
            case 200:
59
                $this->notifySuccess($output["notify"]);
60
                break;
61
62
            case 404:
63
                $this->notifyDanger($output["notify"]);
64
                break;
65
66
            case 500:
67
                $this->notifyWarning($output["notify"]);
68
                break;
69
        }
70
71
        // Return the response.
72
        return $this->redirectToRoute("jquery_datatables_index", ["name" => $name]);
73
    }
74
75
    /**
76
     * Export callback.
77
     *
78
     * @param DataTablesProviderInterface $dtProvider The DataTables provider.
79
     * @param DataTablesRepositoryInterface $repository The DataTables repository.
80
     * @return void
81
     */
82
    protected function exportCallback(DataTablesProviderInterface $dtProvider, DataTablesRepositoryInterface $repository) {
83
84
        // Get the entities manager.
85
        $em = $this->getDoctrine()->getManager();
86
87
        // Open the file.
88
        $stream = fopen("php://output", "w+");
89
90
        // Export the columns.
91
        fputcsv($stream, $dtProvider->exportColumns(), ";");
0 ignored issues
show
Bug introduced by
The method exportColumns() does not seem to exist on object<WBW\Bundle\JQuery...ablesProviderInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
92
93
        // Paginates.
94
        $total = $repository->dataTablesCountExported($dtProvider);
95
        $pages = IntegerUtility::getPagesCount($total, DataTablesRepositoryInterface::REPOSITORY_LIMIT);
96
97
        // Handle each page.
98
        for ($i = 0; $i < $pages; ++$i) {
99
100
            // Get the offset and limit.
101
            list($offset, $limit) = IntegerUtility::getLinesLimit($i, DataTablesRepositoryInterface::REPOSITORY_LIMIT, $total);
102
103
            // Get the export query with offset and limit.
104
            $result = $repository->dataTablesExportAll($dtProvider)
105
                ->setFirstResult($offset) // Use offset
106
                ->setMaxResults($limit) // Use limit
107
                ->getQuery()
108
                ->iterate();
109
110
            // Handle each entity.
111
            while (false !== ($row = $result->next())) {
112
113
                // Export the entity.
114
                fputcsv($stream, $dtProvider->exportRow($row[0]), ";");
0 ignored issues
show
Bug introduced by
The method exportRow() does not seem to exist on object<WBW\Bundle\JQuery...ablesProviderInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
115
116
                // Detach the entity to avoid memory consumption.
117
                $em->detach($row[0]);
118
            }
119
        }
120
        // Close the file.
121
        fclose($stream);
122
    }
123
124
    /**
125
     * Get a DataTables CSV exporter.
126
     *
127
     * @param string $name The provider name.
128
     * @return DataTablesProviderInterface Returns the DataTables CSV exporter.
129
     * @throws UnregisteredDataTablesProviderException Throws an unregistered DataTables provider exception.
130
     * @throws BadDataTablesCSVExporterException Throws a bad DataTables CSV exporter exception.
131
     */
132
    protected function getDataTablesCSVExporter($name) {
133
134
        // Get and check the DataTables provider.
135
        $dtProvider = $this->getDataTablesProvider($name);
136
        if (false === ($dtProvider instanceOf DataTablesCSVExporterInterface)) {
137
            throw new BadDataTablesCSVExporterException($dtProvider);
138
        }
139
140
        // Return the DataTables provider.
141
        return $dtProvider;
142
    }
143
144
    /**
145
     * Get a DataTables entity by id.
146
     *
147
     * @param DataTablesProviderInterface $dtProvider The DataTables provider.
148
     * @param integer $id The entity id.
149
     * @return object Returns the DataTables entity.
150
     * @throws BadDataTablesRepositoryException Throws a bad DataTables repository exception.
151
     * @throws EntityNotFoundException Throws an Entity not found exception.
152
     */
153
    protected function getDataTablesEntityById(DataTablesProviderInterface $dtProvider, $id) {
154
155
        // Log a debug trace.
156
        $this->getLogger()->debug(sprintf("DataTables controller search for an entity [%s]", $id));
157
158
        // Get the repository.
159
        $repository = $this->getDataTablesRepository($dtProvider);
160
161
        // Find and check the entity.
162
        $entity = $repository->find($id);
163
        if (null === $entity) {
164
            throw EntityNotFoundException::fromClassNameAndIdentifier($dtProvider->getEntity(), [$id]);
165
        }
166
167
        // Return the entity.
168
        return $entity;
169
    }
170
171
    /**
172
     * Get the DataTables provider.
173
     *
174
     * @param string $name The provider name.
175
     * @return DataTablesProviderInterface Returns the DataTables provider.
176
     * @throws UnregisteredDataTablesProviderException Throws an unregistered DataTables provider exception.
177
     */
178
    protected function getDataTablesProvider($name) {
179
180
        // Log a debug trace.
181
        $this->getLogger()->debug(sprintf("DataTables controller search for a provider with name \"%s\"", $name));
182
183
        // Get the DataTables provider.
184
        $dtProvider = $this->get(DataTablesManager::SERVICE_NAME)->getProvider($name);
185
186
        // Log a debug trace.
187
        $this->getLogger()->debug(sprintf("DataTables controller found a provider with name \"%s\"", $name));
188
189
        // Return the DataTables provider.
190
        return $dtProvider;
191
    }
192
193
    /**
194
     * Get a DataTables repository.
195
     *
196
     * @param DataTablesProviderInterface The DataTables provider.
197
     * @return EntityRepository Returns the DataTables repository.
198
     * @throws BadDataTablesRepositoryException Throws a bad DataTables repository exception.
199
     */
200
    protected function getDataTablesRepository(DataTablesProviderInterface $dtProvider) {
201
202
        // Log a debug trace.
203
        $this->getLogger()->debug(sprintf("DataTables controller search for a repository with name \"%s\"", $dtProvider->getName()));
204
205
        // Get the entities manager.
206
        $em = $this->getDoctrine()->getManager();
207
208
        // Get and check the entities repository.
209
        $repository = $em->getRepository($dtProvider->getEntity());
210
        if (false === ($repository instanceOf DataTablesRepositoryInterface)) {
211
            throw new BadDataTablesRepositoryException($repository);
212
        }
213
214
        // Return the DataTables repository.
215
        return $repository;
216
    }
217
218
    /**
219
     * Get a DataTables wrapper.
220
     *
221
     * @param DataTablesProviderInterface $dtProvider The DataTables provider.
222
     * @return DataTablesWrapper Returns the DataTables wrapper.
223
     */
224
    protected function getDataTablesWrapper(DataTablesProviderInterface $dtProvider) {
225
226
        // Initialize the URL.
227
        $url = $this->getRouter()->generate("jquery_datatables_index", ["name" => $dtProvider->getName()]);
228
229
        // Initialize the DataTables wrapper.
230
        $dtWrapper = new DataTablesWrapper($dtProvider->getMethod(), $url, $dtProvider->getName());
231
        $dtWrapper->getMapping()->setPrefix($dtProvider->getPrefix());
232
233
        // Handle each column.
234
        foreach ($dtProvider->getColumns() as $dtColumn) {
235
236
            // Log a debug trace.
237
            $this->getLogger()->debug(sprintf("DataTables provider add a column \"%s\"", $dtColumn->getData()));
238
239
            // Add.
240
            $dtWrapper->addColumn($dtColumn);
241
        }
242
243
        // Return the DataTables wrapper.
244
        return $dtWrapper;
245
    }
246
247
    /**
248
     * Get the notification.
249
     *
250
     * @param string $id The notification id.
251
     * @return string Returns the notification.
252
     */
253
    protected function getNotification($id) {
254
        return $this->getTranslator()->trans($id, [], "JQueryDataTablesBundle");
255
    }
256
257
}
258