Completed
Push — master ( 486225...c5b2a4 )
by Arjay
03:07
created

Builder::addIndex()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

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