Completed
Branch develop (80427e)
by Arjay
02:27
created

DataTable::pdf()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
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
     * Export filename.
56
     *
57
     * @var string
58
     */
59
    protected $filename = '';
60
61
    /**
62
     * DataTable constructor.
63
     *
64
     * @param \Yajra\Datatables\Datatables $datatables
65
     * @param \Illuminate\Contracts\View\Factory $viewFactory
66
     */
67
    public function __construct(Datatables $datatables, Factory $viewFactory)
68
    {
69
        $this->datatables  = $datatables;
70
        $this->viewFactory = $viewFactory;
71
    }
72
73
    /**
74
     * Process dataTables needed render output.
75
     *
76
     * @param string $view
77
     * @param array $data
78
     * @param array $mergeData
79
     * @return \Illuminate\Http\JsonResponse|\Illuminate\View\View
80
     */
81
    public function render($view, $data = [], $mergeData = [])
82
    {
83
        if ($this->request()->ajax() && $this->request()->wantsJson()) {
84
            return $this->ajax();
85
        }
86
87
        if ($action = $this->request()->get('action')) {
88
            if ($action == 'print') {
89
                return $this->printPreview();
90
            }
91
92
            return call_user_func_array([$this, $action], []);
93
        }
94
95
        return $this->viewFactory->make($view, $data, $mergeData)->with('dataTable', $this->html());
96
    }
97
98
    /**
99
     * Get Datatables Request instance.
100
     *
101
     * @return \Yajra\Datatables\Request
102
     */
103
    public function request()
104
    {
105
        return $this->datatables->getRequest();
106
    }
107
108
    /**
109
     * Display printable view of datatables.
110
     *
111
     * @return \Illuminate\Contracts\View\View
112
     */
113
    public function printPreview()
114
    {
115
        $data = $this->getDataForPrint();
116
        $view = $this->printPreview ?: 'datatables::print';
117
118
        return $this->viewFactory->make($view, compact('data'));
119
    }
120
121
    /**
122
     * Get mapped columns versus final decorated output.
123
     *
124
     * @return array
125
     */
126
    protected function getDataForPrint()
127
    {
128
        $columns = $this->printColumns();
129
130
        return $this->mapResponseToColumns($columns, 'printable');
131
    }
132
133
    /**
134
     * Get printable columns.
135
     *
136
     * @return array|string
137
     */
138
    protected function printColumns()
139
    {
140
        return is_array($this->printColumns) ? $this->printColumns : $this->getColumnsFromBuilder();
141
    }
142
143
    /**
144
     * Get columns definition from html builder.
145
     *
146
     * @return array
147
     */
148
    protected function getColumnsFromBuilder()
149
    {
150
        return $this->html()->getColumns();
151
    }
152
153
    /**
154
     * Optional method if you want to use html builder.
155
     *
156
     * @return \Yajra\Datatables\Html\Builder
157
     */
158
    public function html()
159
    {
160
        return $this->builder();
161
    }
162
163
    /**
164
     * Get Datatables Html Builder instance.
165
     *
166
     * @return \Yajra\Datatables\Html\Builder
167
     */
168
    public function builder()
169
    {
170
        return $this->datatables->getHtmlBuilder();
171
    }
172
173
    /**
174
     * Map ajax response to columns definition.
175
     *
176
     * @param mixed $columns
177
     * @param string $type
178
     * @return array
179
     */
180
    protected function mapResponseToColumns($columns, $type)
181
    {
182
        return array_map(function ($row) use ($columns, $type) {
183
            if ($columns) {
184
                return (new DataTransformer())->transform($row, $columns, $type);
185
            }
186
187
            return $row;
188
        }, $this->getAjaxResponseData());
189
    }
190
191
    /**
192
     * Get decorated data as defined in datatables ajax response.
193
     *
194
     * @return array
195
     */
196
    protected function getAjaxResponseData()
197
    {
198
        $this->datatables->getRequest()->merge(['length' => -1]);
199
200
        $response = $this->ajax();
201
        $data     = $response->getData(true);
202
203
        return $data['data'];
204
    }
205
206
    /**
207
     * Export results to Excel file.
208
     *
209
     * @return void
210
     */
211
    public function excel()
212
    {
213
        $this->buildExcelFile()->download('xls');
214
    }
215
216
    /**
217
     * Build excel file and prepare for export.
218
     *
219
     * @return \Maatwebsite\Excel\Writers\LaravelExcelWriter
220
     */
221
    protected function buildExcelFile()
222
    {
223
        /** @var \Maatwebsite\Excel\Excel $excel */
224
        $excel = app('excel');
225
226
        return $excel->create($this->getFilename(), function (LaravelExcelWriter $excel) {
227
            $excel->sheet('exported-data', function (LaravelExcelWorksheet $sheet) {
228
                $sheet->fromArray($this->getDataForExport());
229
            });
230
        });
231
    }
232
233
    /**
234
     * Get export filename.
235
     *
236
     * @return string
237
     */
238
    public function getFilename()
239
    {
240
        return $this->filename ?: $this->filename();
241
    }
242
243
    /**
244
     * Set export filename.
245
     *
246
     * @param string $filename
247
     * @return DataTable
248
     */
249
    public function setFilename($filename)
250
    {
251
        $this->filename = $filename;
252
253
        return $this;
254
    }
255
256
    /**
257
     * Get filename for export.
258
     *
259
     * @return string
260
     */
261
    protected function filename()
262
    {
263
        return 'export_' . time();
264
    }
265
266
    /**
267
     * Get mapped columns versus final decorated output.
268
     *
269
     * @return array
270
     */
271
    protected function getDataForExport()
272
    {
273
        $columns = $this->exportColumns();
274
275
        return $this->mapResponseToColumns($columns, 'exportable');
276
    }
277
278
    /**
279
     * Get export columns definition.
280
     *
281
     * @return array|string
282
     */
283
    private function exportColumns()
284
    {
285
        return is_array($this->exportColumns) ? $this->exportColumns : $this->getColumnsFromBuilder();
286
    }
287
288
    /**
289
     * Export results to CSV file.
290
     *
291
     * @return void
292
     */
293
    public function csv()
294
    {
295
        $this->buildExcelFile()->download('csv');
296
    }
297
298
    /**
299
     * Export results to PDF file.
300
     *
301
     * @return void
302
     */
303
    public function pdf()
304
    {
305
        $this->buildExcelFile()->download('pdf');
306
    }
307
308
    /**
309
     * Add basic array query scopes.
310
     *
311
     * @param \Yajra\Datatables\Contracts\DataTableScopeContract $scope
312
     * @return $this
313
     */
314
    public function addScope(DataTableScopeContract $scope)
315
    {
316
        $this->scopes[] = $scope;
317
318
        return $this;
319
    }
320
321
    /**
322
     * Apply query scopes.
323
     *
324
     * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $query
325
     * @return mixed
326
     */
327
    protected function applyScopes($query)
328
    {
329
        foreach ($this->scopes as $scope) {
330
            $scope->apply($query);
331
        }
332
333
        return $query;
334
    }
335
336
    /**
337
     * Get default builder parameters.
338
     *
339
     * @return array
340
     */
341
    protected function getBuilderParameters()
342
    {
343
        return [
344
            'order'   => [[0, 'desc']],
345
            'buttons' => [
346
                'create',
347
                [
348
                    'extend'  => 'collection',
349
                    'text'    => '<i class="fa fa-download"></i> Export',
350
                    'buttons' => [
351
                        'csv',
352
                        'excel',
353
                        'pdf',
354
                    ],
355
                ],
356
                'print',
357
                'reset',
358
                'reload',
359
            ],
360
        ];
361
    }
362
}
363