Passed
Push — master ( 1c101f...c673c5 )
by Matthew
11:42
created

DataTablesRenderer::afterBind()   C

Complexity

Conditions 7
Paths 36

Size

Total Lines 51
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 51
c 0
b 0
f 0
rs 6.9743
cc 7
eloc 35
nc 36
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
    /**
66
     * @param array|null $params
67
     */
68
    public function getParams(array &$params = null)
69
    {
70
        if (null === $params) {
71
            $params = [];
72
        }
73
        parent::getParams($params);
74
        $params['dtc_grid_datatables_css'] = $this->dataTablesCss;
75
        $params['dtc_grid_datatables_js'] = $this->dataTablesJs;
76
        $cssList = ['css/dtc_grid.css'];
77
        $jsList = ['js/jquery.datatable/DT_bootstrap.js',
78
                                        'js/jquery.datatable/DT_action.js',
79
                                        'js/jquery.datatable/jquery.jqtable.js', ];
80
81
        foreach ($cssList as $css) {
82
            $mtime = filemtime(__DIR__.'/../../Resources/public/'.$css);
83
            $params['dtc_grid_local_css'][] = $css.'?v='.$mtime;
84
        }
85
86
        foreach ($jsList as $js) {
87
            $mtime = filemtime(__DIR__.'/../../Resources/public/'.$js);
88
            $params['dtc_grid_local_js'][] = $js.'?v='.$mtime;
89
        }
90
91
        return $params;
92
    }
93
94
    protected function afterBind()
95
    {
96
        $id = $this->gridSource->getDivId();
97
        $this->options['pager'] = "{$id}-pager";
98
99
        $fields = array_keys($this->gridSource->getColumns());
100
101
        // We need to pass filter information here.
102
        $params = array(
103
               'id' => $this->gridSource->getId(),
104
               'renderer' => 'datatables',
105
               'filter' => $this->gridSource->getFilter(),
106
               'parameters' => $this->gridSource->getParameters(),
107
               'order' => $this->gridSource->getOrderBy(),
108
               'fields' => $fields,
109
        );
110
111
        $sortInfo = $this->gridSource->getDefaultSort();
112
        $defaultSortColumn = isset($sortInfo['column']) ? $sortInfo['column'] : null;
113
        $defaultSortDirection = isset($sortInfo['direction']) ? $sortInfo['direction'] : 'ASC';
114
        $defaultSortDirection = strtolower($defaultSortDirection);
115
        $defaultSortColumnIdx = 0;
116
117
        $url = $this->router->generate('dtc_grid_data', $params);
118
        $this->options['sAjaxSource'] = $url;
119
120
        $columnsDef = array();
121
        /** @var AbstractGridColumn $column */
122
        $idx = 0;
123
        foreach ($this->gridSource->getColumns() as $index => $column) {
124
            $info = array();
125
            $name = $column->getField();
126
            $info['bSortable'] = $column->getOption('sortable') ? true : false;
127
            $info['sName'] = $name;
128
129
            if ($width = $column->getOption('width')) {
130
                $info['sWidth'] = $width;
131
            }
132
133
            $info['aTargets'] = array($index);
134
            $info = array_merge($info, $column->getOptions());
135
            $columnsDef[] = $info;
136
            if ($index === $defaultSortColumn) {
137
                $defaultSortColumnIdx = $idx;
138
            }
139
            ++$idx;
140
        }
141
142
        $this->options['order'] = [[$defaultSortColumnIdx, $defaultSortDirection]];
143
        $this->options['aoColumns'] = $columnsDef;
144
    }
145
146
    public function getData()
147
    {
148
        $columns = $this->gridSource->getColumns();
149
        $gridSource = $this->gridSource;
150
        $records = $gridSource->getRecords();
151
        $count = $gridSource->getCount();
152
153
        $retVal = array(
154
                'page' => $gridSource->getPager()
155
                    ->getCurrentPage(),
156
                'total_pages' => $gridSource->getPager()
157
                    ->getTotalPages(),
158
                'iTotalRecords' => (int) $count,
159
                'iTotalDisplayRecords' => $count,
160
                'id' => $gridSource->getId(), // unique id
161
        );
162
163
        $data = array();
164 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...
165
            $info = array();
166
            /** @var AbstractGridColumn $column */
167
            foreach ($columns as $column) {
168
                if (method_exists($column, 'setRouter')) {
169
                    $column->setRouter($this->router);
170
                }
171
                if (method_exists($column, 'setGridSourceId')) {
172
                    $column->setGridSourceId($gridSource->getId());
173
                }
174
                $info[] = $column->format($record, $gridSource);
175
            }
176
177
            $data[] = $info;
178
        }
179
180
        $retVal['aaData'] = $data;
181
182
        return $retVal;
183
    }
184
185
    public function render()
186
    {
187
        $id = $this->gridSource->getDivId();
188
189
        $options = $this->options;
190
        unset($options['table_attr']);
191
192
        $params = array(
193
                'options' => $options,
194
                'table_attr' => $this->options['table_attr'],
195
                'columns' => $this->gridSource->getColumns(),
196
                'id' => $id,
197
        );
198
199
        $template = 'DtcGridBundle:Grid:datatables.html.twig';
200
201
        return $this->twigEngine->render($template, $params);
202
    }
203
}
204