Completed
Push — master ( 7761d4...144654 )
by Song
02:35
created

Exporter::sanitize()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 1
nop 1
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Encore\Admin\Grid;
4
5
use Encore\Admin\Grid;
6
use Illuminate\Support\Arr;
7
8
class Exporter
9
{
10
    /**
11
     * @var Grid
12
     */
13
    protected $grid;
14
15
    /**
16
     * @param Grid $grid
17
     */
18
    public function __construct(Grid $grid)
19
    {
20
        $this->grid = $grid;
21
22
        $this->grid->model()->usePaginate(false);
23
    }
24
25
    /**
26
     * Export csv file.
27
     *
28
     * @return mixed
29
     */
30
    public function export()
31
    {
32
        $titles = [];
33
34
        $filename = $this->grid->model()->eloquent()->getTable().'.csv';
35
36
        $data = $this->grid->processFilter();
37
38
        if (!empty($data)) {
39
40
            $columns = array_dot($this->sanitize($data[0]));
41
42
            $titles = array_keys($columns);
43
        }
44
45
        $output = implode(',', $titles)."\n";
46
47
        foreach ($data as $row) {
48
            $row     = array_only($row, $titles);
49
            $output .= implode(',', array_dot($row))."\n";
50
        }
51
52
        $headers = [
53
            'Content-Encoding'    => 'UTF-8',
54
            'Content-Type'        => 'text/csv;charset=UTF-8',
55
            'Content-Disposition' => "attachment; filename=\"$filename\"",
56
        ];
57
58
        response(rtrim($output, "\n"), 200, $headers)->send();
59
60
        exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method export() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
61
    }
62
63
    /**
64
     * Remove indexed array.
65
     *
66
     * @param array $row
67
     * @return array
68
     */
69
    protected function sanitize(array $row)
70
    {
71
        return collect($row)->reject(function ($val, $_) {
0 ignored issues
show
Unused Code introduced by
The parameter $_ is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
72
73
            return is_array($val) && !Arr::isAssoc($val);
74
75
        })->toArray();
76
    }
77
}
78