Completed
Push — master ( 1b3713...ec9af5 )
by WEBEWEB
01:25
created

DataTablesController::getDataTablesWrapper()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 18
rs 9.4285
cc 2
eloc 6
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 Psr\Log\LoggerInterface;
15
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
16
use Symfony\Component\HttpFoundation\Request;
17
use Symfony\Component\HttpFoundation\Response;
18
use WBW\Bundle\JQuery\DatatablesBundle\API\DataTablesResponse;
19
use WBW\Bundle\JQuery\DatatablesBundle\API\DataTablesWrapper;
20
use WBW\Bundle\JQuery\DatatablesBundle\Exception\BadDataTablesRepositoryException;
21
use WBW\Bundle\JQuery\DatatablesBundle\Exception\UnregisteredDataTablesProviderException;
22
use WBW\Bundle\JQuery\DatatablesBundle\Manager\DataTablesManager;
23
use WBW\Bundle\JQuery\DatatablesBundle\Provider\DataTablesProviderInterface;
24
use WBW\Bundle\JQuery\DatatablesBundle\Repository\DataTablesRepositoryInterface;
25
use WBW\Library\Core\IO\HTTPInterface;
26
27
/**
28
 * DataTables controller.
29
 *
30
 * @author webeweb <https://github.com/webeweb/>
31
 * @package WBW\Bundle\JQuery\DatatablesBundle\Controller
32
 * @final
33
 */
34
final class DataTablesController extends Controller {
35
36
    /**
37
     * Get the DataTables provider.
38
     *
39
     * @return DataTablesProviderInterface Returns the DataTables provider.
40
     */
41
    private function getDataTablesProvider($name) {
42
43
        // Log a debug trace.
44
        $this->getLogger()->debug(sprintf("DataTables controller search for a DataTables provider with name \"%s\"", $name));
45
46
        // Get the DataTables provider.
47
        $dtProvider = $this->get(DataTablesManager::SERVICE_NAME)->getProvider($name);
48
49
        // Log an info trace.
50
        $this->getLogger()->info(sprintf("DataTables controller found a DataTables provider with name \"%s\"", $name));
51
52
        // Return the DataTables provider.
53
        return $dtProvider;
54
    }
55
56
    /**
57
     * Get a DataTables wrapper.
58
     *
59
     * @param DataTablesProviderInterface $dtProvider The DataTables provider.
60
     * @return DataTablesWrapper Returns the DataTables wrapper.
61
     */
62
    private function getDataTablesWrapper(DataTablesProviderInterface $dtProvider) {
63
64
        // Initialize the DataTables wrapper.
65
        $dtWrapper = new DataTablesWrapper($dtProvider->getPrefix(), HTTPInterface::HTTP_METHOD_POST, "jquery_datatables_index", ["name" => $dtProvider->getName()]);
66
67
        // Handle each column.
68
        foreach ($dtProvider->getColumns() as $dtColumn) {
69
70
            // Log a debug trace.
71
            $this->getLogger()->debug(sprintf("DataTables provider add a DataTables column \"%s\"", $dtColumn->getData()));
72
73
            // Add.
74
            $dtWrapper->addColumn($dtColumn);
75
        }
76
77
        // Return the DataTables wrapper.
78
        return $dtWrapper;
79
    }
80
81
    /**
82
     * Get the logger.
83
     *
84
     * @return LoggerInterface Returns the logger.
85
     */
86
    private function getLogger() {
87
        return $this->get("logger");
88
    }
89
90
    /**
91
     * Lists all entities.
92
     *
93
     * @param Request $request The request.
94
     * @param string $name The provider name.
95
     * @return Response Returns the response.
96
     * @throws UnregisteredDataTablesProviderException Throws an unregistered DataTables provider exception.
97
     * @throws BadDataTablesRepositoryException Throws a bad DataTables repository exception.
98
     */
99
    public function indexAction(Request $request, $name) {
100
101
        // Get the provider.
102
        $dtProvider = $this->getDataTablesProvider($name);
103
104
        // Get the wrapper.
105
        $dtWrapper = $this->getDataTablesWrapper($dtProvider);
106
107
        // Check if the request is an XML HTTP request.
108
        if (true === $request->isXmlHttpRequest()) {
109
110
            // Get the entities manager.
111
            $em = $this->getDoctrine()->getManager();
112
113
            // Get and check the entities repository.
114
            $repository = $em->getRepository($dtProvider->getEntity());
115
            if (false === ($repository instanceOf DataTablesRepositoryInterface)) {
116
                throw new BadDataTablesRepositoryException($repository);
117
            }
118
119
            // Parse the request.
120
            $dtWrapper->parse($request);
121
122
            //
123
            $filtered = $repository->dataTablesCountFiltered($dtWrapper);
124
            $total    = $repository->dataTablesCountTotal($dtWrapper);
125
            $entities = $repository->dataTablesFindAll($dtWrapper);
126
127
            // Set the response.
128
            $dtWrapper->getResponse()->setRecordsFiltered($filtered);
129
            $dtWrapper->getResponse()->setRecordsTotal($total);
130
131
            // Handle each entity.
132
            foreach ($entities as $entity) {
133
134
                // Count the rows.
135
                $rows = count($dtWrapper->getResponse()->getData());
136
137
                // Create a row.
138
                $dtWrapper->getResponse()->addRow();
139
140
                // Render each optional parameters.
141
                foreach (DataTablesResponse::dtRow() as $dtRow) {
142
                    $dtWrapper->getResponse()->setRow($dtRow, $dtProvider->renderRow($dtRow, $entity, $rows));
143
                }
144
145
                // Render each column.
146
                foreach ($dtWrapper->getColumns() as $dtColumn) {
147
                    $dtWrapper->getResponse()->setRow($dtColumn->getData(), $dtProvider->renderColumn($dtColumn, $entity));
148
                }
149
            }
150
151
            // Return the response.
152
            return new Response(json_encode($dtWrapper->getResponse()));
153
        }
154
155
        // Initialize the default view.
156
        $dtView = "@JQueryDataTables/DataTables/index.html.twig";
157
158
        // Check the provider view.
159
        if (null !== $dtProvider->getView()) {
160
            $dtView = $dtProvider->getView();
161
        }
162
163
        // Return the response.
164
        return $this->render($dtView, [
165
                "dtWrapper" => $dtWrapper,
166
        ]);
167
    }
168
169
}
170