Completed
Branch scrutinizer (3175f9)
by Arjay
02:35
created

DataTable::buildColumn()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 2
eloc 4
nc 2
nop 3
1
<?php
2
3
namespace Yajra\Datatables\Services;
4
5
use Illuminate\Contracts\View\Factory;
6
use Maatwebsite\Excel\Classes\LaravelExcelWorksheet;
7
use Maatwebsite\Excel\Writers\LaravelExcelWriter;
8
use Yajra\Datatables\Contracts\DataTableButtonsContract;
9
use Yajra\Datatables\Contracts\DataTableContract;
10
use Yajra\Datatables\Contracts\DataTableScopeContract;
11
use Yajra\Datatables\Datatables;
12
use Yajra\Datatables\Transformers\DataTransformer;
13
14
abstract class DataTable implements DataTableContract, DataTableButtonsContract
15
{
16
    /**
17
     * @var \Yajra\Datatables\Datatables
18
     */
19
    protected $datatables;
20
21
    /**
22
     * @var \Illuminate\Contracts\View\Factory
23
     */
24
    protected $viewFactory;
25
26
    /**
27
     * Datatables print preview view.
28
     *
29
     * @var string
30
     */
31
    protected $printPreview;
32
33
    /**
34
     * List of columns to be exported.
35
     *
36
     * @var string|array
37
     */
38
    protected $exportColumns = '*';
39
40
    /**
41
     * List of columns to be printed.
42
     *
43
     * @var string|array
44
     */
45
    protected $printColumns = '*';
46
47
    /**
48
     * Query scopes.
49
     *
50
     * @var \Yajra\Datatables\Contracts\DataTableScopeContract[]
51
     */
52
    protected $scopes = [];
53
54
    /**
55
     * @param \Yajra\Datatables\Datatables $datatables
56
     * @param \Illuminate\Contracts\View\Factory $viewFactory
57
     */
58
    public function __construct(Datatables $datatables, Factory $viewFactory)
59
    {
60
        $this->datatables  = $datatables;
61
        $this->viewFactory = $viewFactory;
62
    }
63
64
    /**
65
     * Render view.
66
     *
67
     * @param $view
68
     * @param array $data
69
     * @param array $mergeData
70
     * @return \Illuminate\Http\JsonResponse|\Illuminate\View\View
71
     */
72
    public function render($view, $data = [], $mergeData = [])
73
    {
74
        if ($this->request()->ajax() && $this->request()->wantsJson()) {
75
            return $this->ajax();
76
        }
77
78
        switch ($this->datatables->getRequest()->get('action')) {
79
            case 'excel':
80
                return $this->excel();
81
82
            case 'csv':
83
                return $this->csv();
84
85
            case 'pdf':
86
                return $this->pdf();
87
88
            case 'print':
89
                return $this->printPreview();
90
91
            default:
92
                return $this->viewFactory->make($view, $data, $mergeData)->with('dataTable', $this->html());
93
        }
94
    }
95
96
    /**
97
     * Get Datatables Request instance.
98
     *
99
     * @return \Yajra\Datatables\Request
100
     */
101
    public function request()
102
    {
103
        return $this->datatables->getRequest();
104
    }
105
106
    /**
107
     * Export results to Excel file.
108
     *
109
     * @return mixed
110
     */
111
    public function excel()
112
    {
113
        return $this->buildExcelFile()->download('xls');
114
    }
115
116
    /**
117
     * Build excel file and prepare for export.
118
     *
119
     * @return mixed
120
     */
121
    protected function buildExcelFile()
122
    {
123
        return app('excel')->create($this->filename(), function (LaravelExcelWriter $excel) {
124
            $excel->sheet('exported-data', function (LaravelExcelWorksheet $sheet) {
125
                $sheet->fromArray($this->getDataForExport());
126
            });
127
        });
128
    }
129
130
    /**
131
     * Get filename for export.
132
     *
133
     * @return string
134
     */
135
    protected function filename()
136
    {
137
        return 'export_' . time();
138
    }
139
140
    /**
141
     * Get mapped columns versus final decorated output.
142
     *
143
     * @return array
144
     */
145 View Code Duplication
    protected function getDataForExport()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
146
    {
147
        return array_map(function ($row) {
148
            if ($columns = $this->exportColumns()) {
149
                return (new DataTransformer())->transform($row, $columns, 'exportable');
150
            }
151
152
            return $row;
153
        }, $this->getAjaxResponseData());
154
    }
155
156
    /**
157
     * Get export columns definition.
158
     *
159
     * @return array|string
160
     */
161
    private function exportColumns()
162
    {
163
        return is_array($this->exportColumns) ? $this->exportColumns : $this->getColumnsFromBuilder();
164
    }
165
166
    /**
167
     * Get columns definition from html builder.
168
     *
169
     * @return array
170
     */
171
    protected function getColumnsFromBuilder()
172
    {
173
        return $this->html()->getColumns();
174
    }
175
176
    /**
177
     * Optional method if you want to use html builder.
178
     *
179
     * @return \Yajra\Datatables\Html\Builder
180
     */
181
    public function html()
182
    {
183
        return $this->builder();
184
    }
185
186
    /**
187
     * Get Datatables Html Builder instance.
188
     *
189
     * @return \Yajra\Datatables\Html\Builder
190
     */
191
    public function builder()
192
    {
193
        return $this->datatables->getHtmlBuilder();
194
    }
195
196
    /**
197
     * Get decorated data as defined in datatables ajax response.
198
     *
199
     * @return mixed
200
     */
201
    protected function getAjaxResponseData()
202
    {
203
        $this->datatables->getRequest()->merge(['length' => -1]);
204
205
        $response = $this->ajax();
206
        $data     = $response->getData(true);
207
208
        return $data['data'];
209
    }
210
211
    /**
212
     * Export results to CSV file.
213
     *
214
     * @return mixed
215
     */
216
    public function csv()
217
    {
218
        return $this->buildExcelFile()->download('csv');
219
    }
220
221
    /**
222
     * Export results to PDF file.
223
     *
224
     * @return mixed
225
     */
226
    public function pdf()
227
    {
228
        return $this->buildExcelFile()->download('pdf');
229
    }
230
231
    /**
232
     * Display printable view of datatables.
233
     *
234
     * @return \Illuminate\Contracts\View\View
235
     */
236
    public function printPreview()
237
    {
238
        $data = $this->getDataForPrint();
239
        $view = $this->printPreview ?: 'datatables::print';
240
241
        return $this->viewFactory->make($view, compact('data'));
242
    }
243
244
    /**
245
     * Get mapped columns versus final decorated output.
246
     *
247
     * @return array
248
     */
249 View Code Duplication
    protected function getDataForPrint()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
250
    {
251
        return array_map(function ($row) {
252
            if ($columns = $this->printColumns()) {
253
                return (new DataTransformer())->transform($row, $columns, 'printable');
254
            }
255
256
            return $row;
257
        }, $this->getAjaxResponseData());
258
    }
259
260
    /**
261
     * Get printable columns.
262
     *
263
     * @return array|string
264
     */
265
    protected function printColumns()
266
    {
267
        return is_array($this->printColumns) ? $this->printColumns : $this->getColumnsFromBuilder();
268
    }
269
270
    /**
271
     * Add basic array query scopes.
272
     *
273
     * @param \Yajra\Datatables\Contracts\DataTableScopeContract $scope
274
     * @return $this
275
     */
276
    public function addScope(DataTableScopeContract $scope)
277
    {
278
        $this->scopes[] = $scope;
279
280
        return $this;
281
    }
282
283
    /**
284
     * Apply query scopes.
285
     *
286
     * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $query
287
     * @return mixed
288
     */
289
    protected function applyScopes($query)
290
    {
291
        foreach ($this->scopes as $scope) {
292
            $scope->apply($query);
293
        }
294
295
        return $query;
296
    }
297
298
    /**
299
     * Get default builder parameters.
300
     *
301
     * @return array
302
     */
303
    protected function getBuilderParameters()
304
    {
305
        return [
306
            'order'   => [[0, 'desc']],
307
            'buttons' => [
308
                'create',
309
                [
310
                    'extend'  => 'collection',
311
                    'text'    => '<i class="fa fa-download"></i> Export',
312
                    'buttons' => [
313
                        'csv',
314
                        'excel',
315
                        'pdf',
316
                    ],
317
                ],
318
                'print',
319
                'reset',
320
                'reload',
321
            ],
322
        ];
323
    }
324
}
325