Completed
Push — master ( a4cfab...4ed449 )
by Matthew
13:53
created

DataTablesRenderer::setMode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Dtc\GridBundle\Grid\Renderer;
4
5
use Dtc\GridBundle\Grid\Column\AbstractGridColumn;
6
7
class DataTablesRenderer extends AbstractJqueryRenderer
8
{
9
    protected $dataTablesCss = [];
10
    protected $dataTablesJs = [];
11
12
    protected $options = array(
13
            'bProcessing' => true,
14
            'searchDelay' => 350,
15
            'table_attr' => array(
16
                    'class' => 'display table table-striped table-bordered small-font',
17
                ),
18
            'sPaginationType' => 'bootstrap',
19
            'bServerSide' => true,
20
            'oLanguage' => array(
21
                'sLengthMenu' => '_MENU_ records per page',
22
            ),
23
            'aoColumns' => array(array(
24
                'bSortable' => false,
25
                'sWidth' => '20%',
26
                'aTargets' => array(-1),
27
            )),
28
        );
29
30
    const MODE_AJAX = 1;
31
    const MODE_SERVER = 2;
32
33
    protected $mode = 1;
34
35
    public function setMode($mode)
36
    {
37
        $this->mode = $mode;
38
    }
39
40
    /**
41
     * Set the type (bootstrap, bootstrap4, foundation, etc.).
42
     *
43
     * @param $type
44
     */
45
    public function setDataTablesCss($css)
46
    {
47
        $this->dataTablesCss = $css;
48
    }
49
50
    public function getDataTablesCss()
51
    {
52
        return $this->dataTablesCss;
53
    }
54
55
    public function setDataTablesJs($js)
56
    {
57
        $this->dataTablesJs = $js;
58
    }
59
60
    public function getDataTablesJs()
61
    {
62
        return $this->dataTablesJs;
63
    }
64
65
    public function setDataTablesClass($class)
66
    {
67
        $this->options['table_attr']['class'] = $class;
68
    }
69
70
    public function getDataTablesClass()
71
    {
72
        return isset($this->options['table_attr']['class']) ? $this->options['table_attr']['class'] : null;
73
    }
74
75
    /**
76
     * @param array|null $params
77
     */
78
    public function getParams(array &$params = null)
79
    {
80
        if (null === $params) {
81
            $params = [];
82
        }
83
        parent::getParams($params);
84
        $params['dtc_grid_datatables_css'] = $this->dataTablesCss;
85
        $params['dtc_grid_datatables_js'] = $this->dataTablesJs;
86
        $cssList = ['css/dtc_grid.css'];
87
        $jsList = ['js/jquery.datatable/DT_bootstrap.js',
88
                                        'js/jquery.datatable/DT_action.js',
89
                                        'js/jquery.datatable/jquery.jqtable.js', ];
90
91
        foreach ($cssList as $css) {
92
            $mtime = filemtime(__DIR__.'/../../Resources/public/'.$css);
93
            $params['dtc_grid_local_css'][] = $css.'?v='.$mtime;
94
        }
95
96
        foreach ($jsList as $js) {
97
            $mtime = filemtime(__DIR__.'/../../Resources/public/'.$js);
98
            $params['dtc_grid_local_js'][] = $js.'?v='.$mtime;
99
        }
100
101
        return $params;
102
    }
103
104
    protected function afterBind()
105
    {
106
        $id = $this->gridSource->getDivId();
107
        $this->options['pager'] = "{$id}-pager";
108
109
        $fields = array_keys($this->gridSource->getColumns());
110
111
        // We need to pass filter information here.
112
        $params = array(
113
               'id' => $this->gridSource->getId(),
114
               'renderer' => 'datatables',
115
               'filter' => $this->gridSource->getFilter(),
116
               'parameters' => $this->gridSource->getParameters(),
117
               'order' => $this->gridSource->getOrderBy(),
118
               'fields' => $fields,
119
        );
120
121
        $sortInfo = $this->gridSource->getDefaultSort();
122
        $defaultSortColumn = isset($sortInfo['column']) ? $sortInfo['column'] : null;
123
        $defaultSortDirection = isset($sortInfo['direction']) ? $sortInfo['direction'] : 'ASC';
124
        $defaultSortDirection = strtolower($defaultSortDirection);
125
        $defaultSortColumnIdx = 0;
126
127
        $url = $this->router->generate('dtc_grid_data', $params);
128
        $this->options['sAjaxSource'] = $url;
129
130
        $columnsDef = array();
131
        /** @var AbstractGridColumn $column */
132
        $idx = 0;
133
        foreach ($this->gridSource->getColumns() as $index => $column) {
134
            $info = array();
135
            $name = $column->getField();
136
            $info['bSortable'] = $column->getOption('sortable') ? true : false;
137
            $info['sName'] = $name;
138
139
            if ($width = $column->getOption('width')) {
140
                $info['sWidth'] = $width;
141
            }
142
143
            $info['aTargets'] = array($index);
144
            $info = array_merge($info, $column->getOptions());
145
            $columnsDef[] = $info;
146
            if ($index === $defaultSortColumn) {
147
                $defaultSortColumnIdx = $idx;
148
            }
149
            ++$idx;
150
        }
151
152
        $this->options['order'] = [[$defaultSortColumnIdx, $defaultSortDirection]];
153
        $this->options['aoColumns'] = $columnsDef;
154
    }
155
156
    public function getData()
157
    {
158
        $columns = $this->gridSource->getColumns();
159
        $gridSource = $this->gridSource;
160
        $records = $gridSource->getRecords();
161
        $count = $gridSource->getCount();
162
163
        $retVal = array(
164
                'page' => $gridSource->getPager()
165
                    ->getCurrentPage(),
166
                'total_pages' => $gridSource->getPager()
167
                    ->getTotalPages(),
168
                'iTotalRecords' => (int) $count,
169
                'iTotalDisplayRecords' => $count,
170
                'id' => $gridSource->getId(), // unique id
171
        );
172
173
        $data = array();
174 View Code Duplication
        foreach ($records as $record) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
175
            $info = array();
176
            /** @var AbstractGridColumn $column */
177
            foreach ($columns as $column) {
178
                if (method_exists($column, 'setRouter')) {
179
                    $column->setRouter($this->router);
180
                }
181
                if (method_exists($column, 'setGridSourceId')) {
182
                    $column->setGridSourceId($gridSource->getId());
183
                }
184
                $info[] = $column->format($record, $gridSource);
185
            }
186
187
            $data[] = $info;
188
        }
189
190
        $retVal['aaData'] = $data;
191
192
        return $retVal;
193
    }
194
195
    public function render()
196
    {
197
        $id = $this->gridSource->getDivId();
198
199
        $options = $this->options;
200
        unset($options['table_attr']);
201
202
        $params = array(
203
                'options' => $options,
204
                'table_attr' => $this->options['table_attr'],
205
                'columns' => $this->gridSource->getColumns(),
206
                'id' => $id,
207
        );
208
209
        $template = 'DtcGridBundle:Grid:datatables.html.twig';
210
211
        return $this->twigEngine->render($template, $params);
212
    }
213
}
214