Completed
Push — master ( 4cc8d8...e56a52 )
by Arjay
04:43
created

Builder::setTitle()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 8
rs 9.4286
cc 2
eloc 4
nc 2
nop 2
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
 */
18
class Builder
19
{
20
    /**
21
     * @var Collection
22
     */
23
    public $collection;
24
25
    /**
26
     * @var Repository
27
     */
28
    public $config;
29
30
    /**
31
     * @var Factory
32
     */
33
    public $view;
34
35
    /**
36
     * @var HtmlBuilder
37
     */
38
    public $html;
39
40
    /**
41
     * @var UrlGenerator
42
     */
43
    public $url;
44
45
    /**
46
     * @var FormBuilder
47
     */
48
    public $form;
49
50
    /**
51
     * @var string|array
52
     */
53
    protected $ajax = '';
54
55
    /**
56
     * @var array
57
     */
58
    protected $tableAttributes = ['class' => 'table', 'id' => 'dataTableBuilder'];
59
60
    /**
61
     * @var string
62
     */
63
    protected $template = '';
64
65
    /**
66
     * @var array
67
     */
68
    protected $attributes = [];
69
70
    /**
71
     * @param Repository $config
72
     * @param Factory $view
73
     * @param HtmlBuilder $html
74
     * @param UrlGenerator $url
75
     * @param FormBuilder $form
76
     */
77
    public function __construct(
78
        Repository $config,
79
        Factory $view,
80
        HtmlBuilder $html,
81
        UrlGenerator $url,
82
        FormBuilder $form
83
    ) {
84
        $this->config     = $config;
85
        $this->view       = $view;
86
        $this->html       = $html;
87
        $this->url        = $url;
88
        $this->collection = new Collection;
89
        $this->form       = $form;
90
    }
91
92
    /**
93
     * Generate DataTable javascript.
94
     *
95
     * @param  null $script
96
     * @param  array $attributes
97
     * @return string
98
     */
99
    public function scripts($script = null, array $attributes = ['type' => 'text/javascript'])
100
    {
101
        $script = $script ?: $this->generateScripts();
102
103
        return '<script' . $this->html->attributes($attributes) . '>' . $script . '</script>' . PHP_EOL;
104
    }
105
106
    /**
107
     * Get generated raw scripts.
108
     *
109
     * @return string
110
     */
111
    public function generateScripts()
112
    {
113
        $args = array_merge(
114
            $this->attributes, [
115
                'ajax'    => $this->ajax,
116
                'columns' => $this->collection->toArray(),
117
            ]
118
        );
119
120
        $parameters = $this->parameterize($args);
121
122
        return sprintf(
123
            $this->template(),
124
            $this->tableAttributes['id'], $parameters
125
        );
126
    }
127
128
    /**
129
     * Generate datatable js parameters.
130
     *
131
     * @param  array $attributes
132
     * @return string
133
     */
134
    public function parameterize($attributes = [])
135
    {
136
        $parameters       = (new Parameters($attributes))->toArray();
137
        $column_functions = [];
138
139
        foreach ($parameters['columns'] as $i => $column) {
140
            if (isset($column['render'])) {
141
                $column_functions[$i]                = $column['render'];
142
                $parameters['columns'][$i]['render'] = "#column_function.{$i}#";
143
            }
144
        }
145
146
        $json = json_encode($parameters);
147
148
        foreach ($column_functions as $i => $function) {
149
            $json = str_replace("\"#column_function.{$i}#\"", $function, $json);
150
        }
151
152
        return $json;
153
    }
154
155
    /**
156
     * Get javascript template to use.
157
     *
158
     * @return string
159
     */
160
    protected function template()
161
    {
162
        return $this->view->make(
163
            $this->template ?: $this->config->get('datatables.script_template', 'datatables::script')
164
        )->render();
165
    }
166
167
    /**
168
     * Add a column in collection using attributes.
169
     *
170
     * @param  array $attributes
171
     * @return $this
172
     */
173
    public function addColumn(array $attributes)
174
    {
175
        $this->collection->push(new Column($attributes));
176
177
        return $this;
178
    }
179
180
    /**
181
     * Add a Column object in collection.
182
     *
183
     * @param \Yajra\Datatables\Html\Column $column
184
     * @return $this
185
     */
186
    public function add(Column $column)
187
    {
188
        $this->collection->push($column);
189
190
        return $this;
191
    }
192
193
    /**
194
     * Set datatables columns from array definition.
195
     *
196
     * @param array $columns
197
     * @return $this
198
     */
199
    public function columns(array $columns)
200
    {
201
        foreach ($columns as $key => $value) {
202
            if (is_array($value)) {
203
                $attributes = array_merge(['name' => $key, 'data' => $key], $this->setTitle($key, $value));
204
            } else {
205
                $attributes = [
206
                    'name'  => $value,
207
                    'data'  => $value,
208
                    'title' => $this->getQualifiedTitle($value),
209
                ];
210
            }
211
212
            $this->collection->push(new Column($attributes));
213
        }
214
215
        return $this;
216
    }
217
218
    /**
219
     * Set title attribute of an array if not set.
220
     *
221
     * @param string $title
222
     * @param array $attributes
223
     * @return array
224
     */
225
    public function setTitle($title, array $attributes)
226
    {
227
        if (! isset($attributes['title'])) {
228
            $attributes['title'] = $this->getQualifiedTitle($title);
229
        }
230
231
        return $attributes;
232
    }
233
234
    /**
235
     * Convert string into a readable title.
236
     *
237
     * @param string $title
238
     * @return string
239
     */
240
    public function getQualifiedTitle($title)
241
    {
242
        return Str::title(str_replace(['.', '_'], ' ', Str::snake($title)));
243
    }
244
245
    /**
246
     * Add a checkbox column.
247
     *
248
     * @param  array $attributes
249
     * @return $this
250
     */
251
    public function addCheckbox(array $attributes = [])
252
    {
253
        $attributes = array_merge(
254
            [
255
                'defaultContent' => '<input type="checkbox" ' . $this->html->attributes($attributes) . '/>',
256
                'title'          => $this->form->checkbox('', '', false, ['id' => 'dataTablesCheckbox']),
257
                'data'           => 'checkbox',
258
                'name'           => 'checkbox',
259
                'orderable'      => false,
260
                'searchable'     => false,
261
                'width'          => '10px',
262
            ], $attributes
263
        );
264
        $this->collection->push(new Column($attributes));
265
266
        return $this;
267
    }
268
269
    /**
270
     * Add a action column.
271
     *
272
     * @param  array $attributes
273
     * @return $this
274
     */
275
    public function addAction(array $attributes = [])
276
    {
277
        $attributes = array_merge(
278
            [
279
                'defaultContent' => '',
280
                'data'           => 'action',
281
                'name'           => 'action',
282
                'title'          => 'Action',
283
                'render'         => null,
284
                'orderable'      => false,
285
                'searchable'     => false,
286
            ], $attributes
287
        );
288
        $this->collection->push(new Column($attributes));
289
290
        return $this;
291
    }
292
293
    /**
294
     * Setup ajax parameter
295
     *
296
     * @param  string|array $attributes
297
     * @return $this
298
     */
299
    public function ajax($attributes)
300
    {
301
        $this->ajax = $attributes;
302
303
        return $this;
304
    }
305
306
    /**
307
     * Generate DataTable's table html.
308
     *
309
     * @param  array $attributes
310
     * @return string
311
     */
312
    public function table(array $attributes = [])
313
    {
314
        $this->tableAttributes = array_merge($this->tableAttributes, $attributes);
315
316
        return '<table ' . $this->html->attributes($this->tableAttributes) . '></table>';
317
    }
318
319
    /**
320
     * Configure DataTable's parameters.
321
     *
322
     * @param  array $attributes
323
     * @return $this
324
     */
325
    public function parameters(array $attributes = [])
326
    {
327
        $this->attributes = array_merge($this->attributes, $attributes);
328
329
        return $this;
330
    }
331
332
    /**
333
     * Set custom javascript template.
334
     *
335
     * @param string $template
336
     * @return $this
337
     */
338
    public function setTemplate($template)
339
    {
340
        $this->template = $template;
341
342
        return $this;
343
    }
344
}
345