Completed
Push — master ( 064006...20444a )
by WEBEWEB
04:40
created

DataTablesController::getDataTablesWrapper()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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