Completed
Push — master ( 3660c3...7e35c8 )
by Arjay
06:44
created

Builder::add()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 6
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
namespace Yajra\Datatables\Html;
4
5
use Collective\Html\FormBuilder;
6
use Collective\Html\HtmlBuilder;
7
use Illuminate\Contracts\Config\Repository;
8
use Illuminate\Contracts\View\Factory;
9
use Illuminate\Routing\UrlGenerator;
10
use Illuminate\Support\Collection;
11
use Illuminate\Support\Str;
12
13
/**
14
 * Class Builder.
15
 *
16
 * @package Yajra\Datatables\Html
17
 * @author  Arjay Angeles <[email protected]>
18
 */
19
class Builder
20
{
21
    /**
22
     * @var Collection
23
     */
24
    public $collection;
25
26
    /**
27
     * @var Repository
28
     */
29
    public $config;
30
31
    /**
32
     * @var Factory
33
     */
34
    public $view;
35
36
    /**
37
     * @var HtmlBuilder
38
     */
39
    public $html;
40
41
    /**
42
     * @var UrlGenerator
43
     */
44
    public $url;
45
46
    /**
47
     * @var FormBuilder
48
     */
49
    public $form;
50
51
    /**
52
     * @var string|array
53
     */
54
    protected $ajax = '';
55
56
    /**
57
     * @var array
58
     */
59
    protected $tableAttributes = ['class' => 'table', 'id' => 'dataTableBuilder'];
60
61
    /**
62
     * @var string
63
     */
64
    protected $template = '';
65
66
    /**
67
     * @var array
68
     */
69
    protected $attributes = [];
70
71
    /**
72
     * Lists of valid DataTables Callbacks.
73
     *
74
     * @link https://datatables.net/reference/option/.
75
     * @var array
76
     */
77
    protected $validCallbacks = [
78
        'createdRow',
79
        'drawCallback',
80
        'footerCallback',
81
        'formatNumber',
82
        'headerCallback',
83
        'infoCallback',
84
        'initComplete',
85
        'preDrawCallback',
86
        'rowCallback',
87
        'stateLoadCallback',
88
        'stateLoaded',
89
        'stateLoadParams',
90
        'stateSaveCallback',
91
        'stateSaveParams',
92
    ];
93
94
    /**
95
     * @param Repository $config
96
     * @param Factory $view
97
     * @param HtmlBuilder $html
98
     * @param UrlGenerator $url
99
     * @param FormBuilder $form
100
     */
101
    public function __construct(
102
        Repository $config,
103
        Factory $view,
104
        HtmlBuilder $html,
105
        UrlGenerator $url,
106
        FormBuilder $form
107
    ) {
108
        $this->config     = $config;
109
        $this->view       = $view;
110
        $this->html       = $html;
111
        $this->url        = $url;
112
        $this->collection = new Collection;
113
        $this->form       = $form;
114
    }
115
116
    /**
117
     * Generate DataTable javascript.
118
     *
119
     * @param  null $script
120
     * @param  array $attributes
121
     * @return string
122
     */
123
    public function scripts($script = null, array $attributes = ['type' => 'text/javascript'])
124
    {
125
        $script = $script ?: $this->generateScripts();
126
127
        return '<script' . $this->html->attributes($attributes) . '>' . $script . '</script>' . PHP_EOL;
128
    }
129
130
    /**
131
     * Get generated raw scripts.
132
     *
133
     * @return string
134
     */
135
    public function generateScripts()
136
    {
137
        $args = array_merge(
138
            $this->attributes, [
139
                'ajax'    => $this->ajax,
140
                'columns' => $this->collection->toArray(),
141
            ]
142
        );
143
144
        $parameters = $this->parameterize($args);
145
146
        return sprintf(
147
            $this->template(),
148
            $this->tableAttributes['id'], $parameters
149
        );
150
    }
151
152
    /**
153
     * Generate DataTables js parameters.
154
     *
155
     * @param  array $attributes
156
     * @return string
157
     */
158
    public function parameterize($attributes = [])
159
    {
160
        $parameters = (new Parameters($attributes))->toArray();
161
162
        list($columnFunctions, $parameters) = $this->encodeColumnFunctions($parameters);
163
        list($callbackFunctions, $parameters) = $this->encodeCallbackFunctions($parameters);
164
165
        $json = json_encode($parameters);
166
167
        $json = $this->decodeColumnFunctions($columnFunctions, $json);
168
        $json = $this->decodeCallbackFunctions($callbackFunctions, $json);
169
170
        return $json;
171
    }
172
173
    /**
174
     * Encode columns render function.
175
     *
176
     * @param array $parameters
177
     * @return array
178
     */
179
    protected function encodeColumnFunctions(array $parameters)
180
    {
181
        $columnFunctions = [];
182
        foreach ($parameters['columns'] as $i => $column) {
183
            unset($parameters['columns'][$i]['exportable']);
184
            unset($parameters['columns'][$i]['printable']);
185
            unset($parameters['columns'][$i]['footer']);
186
187
            if (isset($column['render'])) {
188
                $columnFunctions[$i]                 = $column['render'];
189
                $parameters['columns'][$i]['render'] = "#column_function.{$i}#";
190
            }
191
        }
192
193
        return [$columnFunctions, $parameters];
194
    }
195
196
    /**
197
     * Encode DataTables callbacks function.
198
     *
199
     * @param array $parameters
200
     * @return array
201
     */
202
    protected function encodeCallbackFunctions(array $parameters)
203
    {
204
        $callbackFunctions = [];
205
        foreach ($parameters as $key => $callback) {
206
            if (in_array($key, $this->validCallbacks)) {
207
                $callbackFunctions[$key] = $this->compileCallback($callback);
208
                $parameters[$key]        = "#callback_function.{$key}#";
209
            }
210
        }
211
212
        return [$callbackFunctions, $parameters];
213
    }
214
215
    /**
216
     * Compile DataTable callback value.
217
     *
218
     * @param mixed $callback
219
     * @return mixed|string
220
     */
221
    private function compileCallback($callback)
222
    {
223
        if (is_callable($callback)) {
224
            return value($callback);
225
        } elseif ($this->view->exists($callback)) {
226
            return $this->view->make($callback)->render();
227
        }
228
229
        return $callback;
230
    }
231
232
    /**
233
     * Decode columns render functions.
234
     *
235
     * @param array $columnFunctions
236
     * @param string $json
237
     * @return string
238
     */
239
    protected function decodeColumnFunctions(array $columnFunctions, $json)
240
    {
241
        foreach ($columnFunctions as $i => $function) {
242
            $json = str_replace("\"#column_function.{$i}#\"", $function, $json);
243
        }
244
245
        return $json;
246
    }
247
248
    /**
249
     * Decode DataTables callbacks function.
250
     *
251
     * @param array $callbackFunctions
252
     * @param string $json
253
     * @return string
254
     */
255
    protected function decodeCallbackFunctions(array $callbackFunctions, $json)
256
    {
257
        foreach ($callbackFunctions as $i => $function) {
258
            $json = str_replace("\"#callback_function.{$i}#\"", $function, $json);
259
        }
260
261
        return $json;
262
    }
263
264
    /**
265
     * Get javascript template to use.
266
     *
267
     * @return string
268
     */
269
    protected function template()
270
    {
271
        return $this->view->make(
272
            $this->template ?: $this->config->get('datatables.script_template', 'datatables::script')
273
        )->render();
274
    }
275
276
    /**
277
     * Add a column in collection using attributes.
278
     *
279
     * @param  array $attributes
280
     * @return $this
281
     */
282
    public function addColumn(array $attributes)
283
    {
284
        $this->collection->push(new Column($attributes));
285
286
        return $this;
287
    }
288
289
    /**
290
     * Add a Column object in collection.
291
     *
292
     * @param \Yajra\Datatables\Html\Column $column
293
     * @return $this
294
     */
295
    public function add(Column $column)
296
    {
297
        $this->collection->push($column);
298
299
        return $this;
300
    }
301
302
    /**
303
     * Set datatables columns from array definition.
304
     *
305
     * @param array $columns
306
     * @return $this
307
     */
308
    public function columns(array $columns)
309
    {
310
        foreach ($columns as $key => $value) {
311
            if (! is_a($value, Column::class)) {
312
                if (is_array($value)) {
313
                    $attributes = array_merge(['name' => $key, 'data' => $key], $this->setTitle($key, $value));
314
                } else {
315
                    $attributes = [
316
                        'name'  => $value,
317
                        'data'  => $value,
318
                        'title' => $this->getQualifiedTitle($value),
319
                    ];
320
                }
321
322
                $this->collection->push(new Column($attributes));
323
            } else {
324
                $this->collection->push($value);
325
            }
326
        }
327
328
        return $this;
329
    }
330
331
    /**
332
     * Set title attribute of an array if not set.
333
     *
334
     * @param string $title
335
     * @param array $attributes
336
     * @return array
337
     */
338
    public function setTitle($title, array $attributes)
339
    {
340
        if (! isset($attributes['title'])) {
341
            $attributes['title'] = $this->getQualifiedTitle($title);
342
        }
343
344
        return $attributes;
345
    }
346
347
    /**
348
     * Convert string into a readable title.
349
     *
350
     * @param string $title
351
     * @return string
352
     */
353
    public function getQualifiedTitle($title)
354
    {
355
        return Str::title(str_replace(['.', '_'], ' ', Str::snake($title)));
356
    }
357
358
    /**
359
     * Add a checkbox column.
360
     *
361
     * @param  array $attributes
362
     * @return $this
363
     */
364
    public function addCheckbox(array $attributes = [])
365
    {
366
        $attributes = array_merge([
367
            'defaultContent' => '<input type="checkbox" ' . $this->html->attributes($attributes) . '/>',
368
            'title'          => $this->form->checkbox('', '', false, ['id' => 'dataTablesCheckbox']),
369
            'data'           => 'checkbox',
370
            'name'           => 'checkbox',
371
            'orderable'      => false,
372
            'searchable'     => false,
373
            'exportable'     => false,
374
            'printable'      => true,
375
            'width'          => '10px',
376
        ], $attributes);
377
        $this->collection->push(new Column($attributes));
378
379
        return $this;
380
    }
381
382
    /**
383
     * Add a action column.
384
     *
385
     * @param  array $attributes
386
     * @return $this
387
     */
388
    public function addAction(array $attributes = [])
389
    {
390
        $attributes = array_merge([
391
            'defaultContent' => '',
392
            'data'           => 'action',
393
            'name'           => 'action',
394
            'title'          => 'Action',
395
            'render'         => null,
396
            'orderable'      => false,
397
            'searchable'     => false,
398
            'exportable'     => false,
399
            'printable'      => true,
400
            'footer'         => '',
401
        ], $attributes);
402
        $this->collection->push(new Column($attributes));
403
404
        return $this;
405
    }
406
407
    /**
408
     * Setup ajax parameter
409
     *
410
     * @param  string|array $attributes
411
     * @return $this
412
     */
413
    public function ajax($attributes)
414
    {
415
        $this->ajax = $attributes;
416
417
        return $this;
418
    }
419
420
    /**
421
     * Generate DataTable's table html.
422
     *
423
     * @param array $attributes
424
     * @param bool $drawFooter
425
     * @return string
426
     */
427
    public function table(array $attributes = [], $drawFooter = false)
428
    {
429
        $this->tableAttributes = array_merge($this->tableAttributes, $attributes);
430
431
        $th       = $this->compileTableHeaders();
432
        $htmlAttr = $this->html->attributes($this->tableAttributes);
433
434
        $tableHtml = '<table ' . $htmlAttr . '>';
435
        $tableHtml .= '<thead><tr>' . implode('', $th) . '</tr></thead>';
436
        if ($drawFooter) {
437
            $tf = $this->compileTableFooter();
438
            $tableHtml .= '<tfoot><tr>' . implode('', $tf) . '</tr></tfoot>';
439
        }
440
        $tableHtml .= '</table>';
441
442
        return $tableHtml;
443
    }
444
445
    /**
446
     * Compile table headers and to support responsive extension.
447
     *
448
     * @return array
449
     */
450
    private function compileTableHeaders()
451
    {
452
        $th = [];
453
        foreach ($this->collection->toArray() as $row) {
454
            $thAttr = $this->html->attributes(
455
                array_only($row, ['class', 'id', 'width', 'style', 'data-class', 'data-hide'])
456
            );
457
            $th[]   = '<th ' . $thAttr . '>' . $row['title'] . '</th>';
458
        }
459
460
        return $th;
461
    }
462
463
    /**
464
     * Compile table footer contents.
465
     *
466
     * @return array
467
     */
468
    private function compileTableFooter()
469
    {
470
        $footer = [];
471
        foreach ($this->collection->toArray() as $row) {
472
            $footer[] = '<th>' . $row['footer'] . '</th>';
473
        }
474
475
        return $footer;
476
    }
477
478
    /**
479
     * Configure DataTable's parameters.
480
     *
481
     * @param  array $attributes
482
     * @return $this
483
     */
484
    public function parameters(array $attributes = [])
485
    {
486
        $this->attributes = array_merge($this->attributes, $attributes);
487
488
        return $this;
489
    }
490
491
    /**
492
     * Set custom javascript template.
493
     *
494
     * @param string $template
495
     * @return $this
496
     */
497
    public function setTemplate($template)
498
    {
499
        $this->template = $template;
500
501
        return $this;
502
    }
503
504
    /**
505
     * Get collection of columns.
506
     *
507
     * @return Collection
508
     */
509
    public function getColumns()
510
    {
511
        return $this->collection;
512
    }
513
}
514