Builder   A
last analyzed

Complexity

Total Complexity 24

Size/Duplication

Total Lines 276
Duplicated Lines 1.81 %

Coupling/Cohesion

Components 1
Dependencies 17

Importance

Changes 0
Metric Value
wmc 24
lcom 1
cbo 17
dl 5
loc 276
rs 10
c 0
b 0
f 0

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A scripts() 0 7 2
A generateScripts() 0 8 1
A generateJson() 0 16 1
A parameterize() 5 26 4
A isCallbackFunction() 0 10 3
A template() 0 6 2
A table() 0 19 3
A parameters() 0 6 1
A setTemplate() 0 6 1
A makeDataScript() 0 10 3
A asOptions() 0 4 1
A asFunction() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Yajra\DataTables\Html;
4
5
use Collective\Html\HtmlBuilder;
6
use Illuminate\Contracts\Config\Repository;
7
use Illuminate\Contracts\View\Factory;
8
use Illuminate\Support\Arr;
9
use Illuminate\Support\Collection;
10
use Illuminate\Support\HtmlString;
11
use Illuminate\Support\Str;
12
use Illuminate\Support\Traits\Macroable;
13
14
class Builder
15
{
16
    use Macroable;
17
    use HasOptions;
18
    use HasTable;
19
    use HasEditor;
20
    use Columns\Index;
21
    use Columns\Action;
22
    use Columns\Checkbox;
23
24
    // Select plugin constants.
25
    const SELECT_STYLE_API         = 'api';
26
    const SELECT_STYLE_SINGLE      = 'single';
27
    const SELECT_STYLE_MULTI       = 'multi';
28
    const SELECT_STYLE_OS          = 'os';
29
    const SELECT_STYLE_MULTI_SHIFT = 'multi+shift';
30
    const SELECT_ITEMS_ROW         = 'row';
31
    const SELECT_ITEMS_COLUMN      = 'column';
32
    const SELECT_ITEMS_CELL        = 'cell';
33
34
    /**
35
     * @var Collection
36
     */
37
    public $collection;
38
39
    /**
40
     * @var Repository
41
     */
42
    public $config;
43
44
    /**
45
     * @var Factory
46
     */
47
    public $view;
48
49
    /**
50
     * @var HtmlBuilder
51
     */
52
    public $html;
53
54
    /**
55
     * @var array
56
     */
57
    protected $tableAttributes = [];
58
59
    /**
60
     * @var string
61
     */
62
    protected $template = '';
63
64
    /**
65
     * @var array
66
     */
67
    protected $attributes = [];
68
69
    /**
70
     * @param Repository $config
71
     * @param Factory $view
72
     * @param HtmlBuilder $html
73
     */
74
    public function __construct(Repository $config, Factory $view, HtmlBuilder $html)
75
    {
76
        $this->config = $config;
77
        $this->view = $view;
78
        $this->html = $html;
79
        $this->collection = new Collection;
80
        $this->tableAttributes = $this->config->get('datatables-html.table', []);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->config->get('data...s-html.table', array()) of type * is incompatible with the declared type array of property $tableAttributes.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
81
    }
82
83
    /**
84
     * Generate DataTable javascript.
85
     *
86
     * @param  null $script
87
     * @param  array $attributes
88
     * @return \Illuminate\Support\HtmlString
89
     * @throws \Exception
90
     */
91
    public function scripts($script = null, array $attributes = ['type' => 'text/javascript'])
92
    {
93
        $script = $script ?: $this->generateScripts();
94
        $attributes = $this->html->attributes($attributes);
95
96
        return new HtmlString("<script{$attributes}>{$script}</script>\n");
97
    }
98
99
    /**
100
     * Get generated raw scripts.
101
     *
102
     * @return \Illuminate\Support\HtmlString
103
     * @throws \Exception
104
     */
105
    public function generateScripts()
106
    {
107
        $parameters = $this->generateJson();
108
109
        return new HtmlString(
110
            sprintf($this->template(), $this->getTableAttribute('id'), $parameters)
111
        );
112
    }
113
114
    /**
115
     * Get generated json configuration.
116
     *
117
     * @return string
118
     */
119
    public function generateJson()
120
    {
121
        $args = array_merge(
122
            $this->attributes, [
123
                'ajax' => $this->ajax,
124
                'columns' => $this->collection->map(function (Column $column) {
125
                    $column = $column->toArray();
126
                    unset($column['attributes']);
127
128
                    return $column;
129
                })->toArray(),
130
            ]
131
        );
132
133
        return $this->parameterize($args);
134
    }
135
136
    /**
137
     * Generate DataTables js parameters.
138
     *
139
     * @param  array $attributes
140
     * @return string
141
     */
142
    public function parameterize($attributes = [])
143
    {
144
        $parameters = (new Parameters($attributes))->toArray();
145
146
        $values = [];
147
        $replacements = [];
148
149
        foreach (Arr::dot($parameters) as $key => $value) {
0 ignored issues
show
Documentation introduced by
$parameters is of type array, but the function expects a object<Illuminate\Support\iterable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
150 View Code Duplication
            if ($this->isCallbackFunction($value, $key)) {
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...
151
                $values[] = trim($value);
152
                Arr::set($parameters, $key, '%' . $key . '%');
153
                $replacements[] = '"%' . $key . '%"';
154
            }
155
        }
156
157
        $new = [];
158
        foreach ($parameters as $key => $value) {
159
            Arr::set($new, $key, $value);
160
        }
161
162
        $json = json_encode($new);
163
164
        $json = str_replace($replacements, $values, $json);
165
166
        return $json;
167
    }
168
169
    /**
170
     * Check if given key & value is a valid callback js function.
171
     *
172
     * @param string $value
173
     * @param string $key
174
     * @return bool
175
     */
176
    protected function isCallbackFunction($value, $key)
177
    {
178
        if (empty($value)) {
179
            return false;
180
        }
181
182
        $callbacks = $this->config->get('datatables-html.callback', ['$', '$.', 'function']);
183
184
        return Str::startsWith(trim($value), $callbacks) || Str::contains($key, 'editor');
185
    }
186
187
    /**
188
     * Get javascript template to use.
189
     *
190
     * @return string
191
     */
192
    protected function template()
193
    {
194
        $template = $this->template ?: $this->config->get('datatables-html.script', 'datatables::script');
195
196
        return $this->view->make($template, ['editors' => $this->editors])->render();
197
    }
198
199
    /**
200
     * Generate DataTable's table html.
201
     *
202
     * @param array $attributes
203
     * @param bool $drawFooter
204
     * @param bool $drawSearch
205
     * @return \Illuminate\Support\HtmlString
206
     */
207
    public function table(array $attributes = [], $drawFooter = false, $drawSearch = false)
208
    {
209
        $this->setTableAttributes($attributes);
210
211
        $th = $this->compileTableHeaders();
212
        $htmlAttr = $this->html->attributes($this->tableAttributes);
213
214
        $tableHtml = '<table ' . $htmlAttr . '>';
215
        $searchHtml = $drawSearch ? '<tr class="search-filter">' . implode('',
216
                $this->compileTableSearchHeaders()) . '</tr>' : '';
217
        $tableHtml .= '<thead><tr>' . implode('', $th) . '</tr>' . $searchHtml . '</thead>';
218
        if ($drawFooter) {
219
            $tf = $this->compileTableFooter();
220
            $tableHtml .= '<tfoot><tr>' . implode('', $tf) . '</tr></tfoot>';
221
        }
222
        $tableHtml .= '</table>';
223
224
        return new HtmlString($tableHtml);
225
    }
226
227
    /**
228
     * Configure DataTable's parameters.
229
     *
230
     * @param  array $attributes
231
     * @return $this
232
     */
233
    public function parameters(array $attributes = [])
234
    {
235
        $this->attributes = array_merge($this->attributes, $attributes);
236
237
        return $this;
238
    }
239
240
    /**
241
     * Set custom javascript template.
242
     *
243
     * @param string $template
244
     * @return $this
245
     */
246
    public function setTemplate($template)
247
    {
248
        $this->template = $template;
249
250
        return $this;
251
    }
252
253
    /**
254
     * Make a data script to be appended on ajax request of dataTables.
255
     *
256
     * @param array $data
257
     * @return string
258
     */
259
    protected function makeDataScript(array $data)
260
    {
261
        $script = '';
262
        foreach ($data as $key => $value) {
263
            $dataValue = $this->isCallbackFunction($value, $key) ? $value : "'{$value}'";
264
            $script .= PHP_EOL . "data.{$key} = {$dataValue};";
265
        }
266
267
        return $script;
268
    }
269
270
    /**
271
     * Generate scripts that sets the dataTables options into a variable.
272
     *
273
     * @return $this
274
     */
275
    public function asOptions()
276
    {
277
        return $this->setTemplate('datatables::options');
278
    }
279
280
    /**
281
     * Wrap dataTable scripts with a function.
282
     *
283
     * @return $this
284
     */
285
    public function asFunction()
286
    {
287
        return $this->setTemplate('datatables::function');
288
    }
289
}
290