Passed
Push — main ( 302427...b5b644 )
by Yaroslav
14:44
created

ExportToExcelAction::askForColumns()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 30
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
nc 2
nop 3
dl 0
loc 30
c 1
b 0
f 0
cc 4
ccs 0
cts 22
cp 0
crap 20
rs 9.7
1
<?php
2
3
4
namespace NovaExportConfiguration\Nova\Actions;
5
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Support\Arr;
8
use Illuminate\Support\Facades\Auth;
9
use Illuminate\Support\Str;
10
use Laravel\Nova\Actions\Action;
11
use Laravel\Nova\Fields\BooleanGroup;
12
use Laravel\Nova\Fields\Field;
13
use Laravel\Nova\Http\Requests\ActionRequest;
14
use Laravel\Nova\Nova;
15
use Maatwebsite\Excel\Facades\Excel;
16
use Maatwebsite\LaravelNovaExcel\Requests\ExportActionRequest;
17
use NovaExportConfiguration\Models\ExportStoredFile;
18
19
class ExportToExcelAction extends \Maatwebsite\LaravelNovaExcel\Actions\ExportToExcel
20
{
21
    protected bool $columnsSelected = false;
22
    protected array $columns;
23
24
    protected ?\Closure $postReplaceFieldValuesWhenOnResource = null;
25
26
    public function askForColumns(array $options, string $label = null, callable $callback = null): static
27
    {
28
        $this->columns = collect($options)
0 ignored issues
show
Bug introduced by
$options of type array is incompatible with the type Illuminate\Contracts\Support\Arrayable expected by parameter $value of collect(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

28
        $this->columns = collect(/** @scrutinizer ignore-type */ $options)
Loading history...
29
            ->mapWithKeys(function ($value, $key) {
30
                if (is_integer($key)) {
31
                    return [$value => Nova::humanize(Str::camel($value))];
32
                }
33
34
                return [$key => $value];
35
            })
36
            ->all();
37
38
        $field = BooleanGroup::make(
39
            __($label ?: 'Columns')
40
        )
41
            ->options($this->columns)
0 ignored issues
show
Bug introduced by
$this->columns of type array is incompatible with the type Closure expected by parameter $options of Laravel\Nova\Fields\BooleanGroup::options(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

41
            ->options(/** @scrutinizer ignore-type */ $this->columns)
Loading history...
42
            ->default(function () {
43
                return array_combine(
44
                    array_keys($this->columns),
45
                    array_fill(0, count($this->columns), true)
46
                );
47
            });
48
49
        if (is_callable($callback)) {
50
            $callback($field);
51
        }
52
53
        $this->actionFields[] = $field;
54
55
        return $this;
56
    }
57
58
    public function handleRequest(ActionRequest $request)
59
    {
60
        $this->handleColumns($request);
61
62
        return parent::handleRequest($request);
63
    }
64
65
    public function handle(ActionRequest $request, Action $exportable): mixed
66
    {
67
        $resource = $request->resource();
68
        $type     = $resource::uriKey();
69
        $name     = $this->getFilename();
70
        $filename = date('Y/m/d/') . Str::uuid() . '.' . $this->getDefaultExtension();
71
        $disk     = $this->getDisk() ?: config('nova-export-configuration.defaults.disk_export_action');
72
73
        $response = Excel::store(
74
            $exportable,
75
            $filename,
76
            $disk,
77
            $this->getWriterType()
78
        );
79
80
        if (false === $response) {
81
            return \is_callable($this->onFailure)
82
                ? ($this->onFailure)($request, $response)
83
                : Action::danger(__('Resource could not be exported.'));
0 ignored issues
show
Bug introduced by
It seems like __('Resource could not be exported.') can also be of type array; however, parameter $name of Laravel\Nova\Actions\Action::danger() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

83
                : Action::danger(/** @scrutinizer ignore-type */ __('Resource could not be exported.'));
Loading history...
84
        }
85
86
        $dbExport       = new ExportStoredFile();
87
        $dbExport->type = $type;
0 ignored issues
show
Bug introduced by
The property type does not seem to exist on NovaExportConfiguration\Models\ExportStoredFile. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
88
        $dbExport->disk = $disk;
0 ignored issues
show
Bug introduced by
The property disk does not seem to exist on NovaExportConfiguration\Models\ExportStoredFile. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
89
        $dbExport->path = $filename;
0 ignored issues
show
Bug introduced by
The property path does not seem to exist on NovaExportConfiguration\Models\ExportStoredFile. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
90
        $dbExport->name = $name;
0 ignored issues
show
Bug introduced by
The property name does not seem to exist on NovaExportConfiguration\Models\ExportStoredFile. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
91
        $dbExport->meta->setAttribute('fields', $request->resolveFields());
0 ignored issues
show
Bug introduced by
The property meta does not seem to exist on NovaExportConfiguration\Models\ExportStoredFile. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
92
        $dbExport->meta->setAttribute('filters', $request->filters);
93
        if ($user = Auth::user()) {
94
            $dbExport->meta->toMorph('author', $user);
95
        }
96
97
        $dbExport->save();
98
99
        return \is_callable($this->onSuccess)
100
            ? ($this->onSuccess)($request, $response)
101
            : Action::message(__('Data exported to file.'));
0 ignored issues
show
Bug introduced by
It seems like __('Data exported to file.') can also be of type array; however, parameter $message of Laravel\Nova\Actions\Action::message() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

101
            : Action::message(/** @scrutinizer ignore-type */ __('Data exported to file.'));
Loading history...
102
    }
103
104
    protected function handleColumns(ActionRequest $request): void
105
    {
106
        $fields = $request->resolveFields();
107
108
        if ($columns = $fields->get('columns')) {
109
            $activeColumns = array_keys(array_filter($columns));
0 ignored issues
show
Bug introduced by
$columns of type Illuminate\Support\TGetD...luminate\Support\TValue is incompatible with the type array expected by parameter $array of array_filter(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

109
            $activeColumns = array_keys(array_filter(/** @scrutinizer ignore-type */ $columns));
Loading history...
110
            if (count($activeColumns) > 0) {
111
                $this->columnsSelected = true;
112
                $this->only            = $activeColumns;
113
            }
114
        }
115
    }
116
117
    protected function handleHeadings($query, ExportActionRequest $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

117
    protected function handleHeadings($query, /** @scrutinizer ignore-unused */ ExportActionRequest $request)

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

Loading history...
Unused Code introduced by
The parameter $query is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

117
    protected function handleHeadings(/** @scrutinizer ignore-unused */ $query, ExportActionRequest $request)

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

Loading history...
118
    {
119
        if ($this->columnsSelected) {
120
            $this->headings = Arr::only($this->columns, $this->only);
121
        } else {
122
            $this->headings = collect($this->only)
0 ignored issues
show
Bug introduced by
$this->only of type array is incompatible with the type Illuminate\Contracts\Support\Arrayable expected by parameter $value of collect(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

122
            $this->headings = collect(/** @scrutinizer ignore-type */ $this->only)
Loading history...
123
                ->map(function ($item) {
124
                    return Str::title($item);
125
                })
126
                ->toArray();
127
        }
128
    }
129
130
    protected function isExportableField(Field $field): bool
131
    {
132
        if ($field->attribute == 'email') {
133
            return false;
134
        }
135
136
        return parent::isExportableField($field);
137
    }
138
139
    public function setPostReplaceFieldValuesWhenOnResource(?\Closure $closure): static
140
    {
141
        $this->postReplaceFieldValuesWhenOnResource = $closure;
142
143
        return $this;
144
    }
145
146
147
    protected function replaceFieldValuesWhenOnResource(Model $model, array $only = []): array
148
    {
149
        $row = parent::replaceFieldValuesWhenOnResource($model, $only);
150
151
        if (is_callable($this->postReplaceFieldValuesWhenOnResource)) {
152
            $row = call_user_func_array(
153
                $this->postReplaceFieldValuesWhenOnResource,
0 ignored issues
show
Bug introduced by
It seems like $this->postReplaceFieldValuesWhenOnResource can also be of type null; however, parameter $callback of call_user_func_array() does only seem to accept callable, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

153
                /** @scrutinizer ignore-type */ $this->postReplaceFieldValuesWhenOnResource,
Loading history...
154
                [$row, $model, $only,]
155
            );
156
        }
157
158
        return $row;
159
    }
160
}
161