-
Notifications
You must be signed in to change notification settings - Fork 73
/
ExportToExcel.php
347 lines (297 loc) 路 8.87 KB
/
ExportToExcel.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
<?php
namespace Maatwebsite\LaravelNovaExcel\Actions;
use Laravel\Nova\Nova;
use Laravel\Nova\Resource;
use Laravel\Nova\Fields\Field;
use Laravel\Nova\Actions\Action;
use Laravel\Nova\Fields\Gravatar;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Eloquent\Model;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithMapping;
use Laravel\Nova\Http\Requests\ActionRequest;
use Maatwebsite\LaravelNovaExcel\Concerns\Only;
use Maatwebsite\LaravelNovaExcel\Concerns\Except;
use Maatwebsite\Excel\Concerns\WithCustomChunkSize;
use Maatwebsite\LaravelNovaExcel\Concerns\WithDisk;
use Maatwebsite\LaravelNovaExcel\Concerns\WithFilename;
use Maatwebsite\LaravelNovaExcel\Concerns\WithHeadings;
use Maatwebsite\LaravelNovaExcel\Concerns\WithChunkCount;
use Maatwebsite\LaravelNovaExcel\Concerns\WithWriterType;
use Maatwebsite\LaravelNovaExcel\Requests\SerializedRequest;
use Maatwebsite\LaravelNovaExcel\Interactions\AskForFilename;
use Maatwebsite\LaravelNovaExcel\Requests\ExportActionRequest;
use Maatwebsite\LaravelNovaExcel\Interactions\AskForWriterType;
use Maatwebsite\Excel\Concerns\WithHeadings as WithHeadingsConcern;
use Maatwebsite\LaravelNovaExcel\Requests\ExportActionRequestFactory;
class ExportToExcel extends Action implements FromQuery, WithCustomChunkSize, WithHeadingsConcern, WithMapping
{
use AskForFilename,
AskForWriterType,
Except,
Only,
WithChunkCount,
WithDisk,
WithFilename,
WithHeadings,
WithWriterType;
/**
* @var ExportActionRequest|ActionRequest
*/
protected $request;
/**
* @var string
*/
protected $resource;
/**
* @var Builder
*/
protected $query;
/**
* @var Field[]
*/
protected $actionFields;
/**
* @var callable|null
*/
protected $onSuccess;
/**
* @var callable|null
*/
protected $onFailure;
/**
* @var array
*/
protected $serializedResources = [];
/**
* @var array
*/
protected $serializedResourcesByModels = [];
/**
* Remove some attributes from this class when serializing,
* so the action can be queued as exportable.
* Serialize the request, so we keep information about
* the resource and lens in the queued jobs.
*
* @return array
*/
public function __sleep()
{
if (!$this->request instanceof SerializedRequest) {
$this->request = SerializedRequest::serialize($this->request);
}
// Remember list of all available resources when serializing the job.
$this->serializedResources = Nova::$resources;
$this->serializedResourcesByModels = Nova::$resourcesByModel;
return ['headings', 'except', 'only', 'onlyIndexFields', 'request', 'resource', 'serializedResources'];
}
/**
* Unserialize the action.
*/
public function __wakeup()
{
if ($this->request instanceof SerializedRequest) {
$this->request = $this->request->unserialize();
}
// Restore the available resources.
Nova::resources($this->serializedResources);
Nova::$resourcesByModel = $this->serializedResourcesByModels;
$this->serializedResources = [];
$this->serializedResourcesByModels = [];
}
/**
* Execute the action for the given request.
*
* @param \Laravel\Nova\Http\Requests\ActionRequest $request
*
* @return mixed
*/
public function handleRequest(ActionRequest $request)
{
$this->handleWriterType($request);
$this->handleFilename($request);
$this->resource = $request->resource();
$this->request = ExportActionRequestFactory::make($request);
$query = $this->request->toExportQuery();
$this->handleOnly($this->request);
$this->handleHeadings($query, $this->request);
return $this->handle($request, $this->withQuery($query));
}
/**
* @param ActionRequest $request
* @param Action $exportable
*
* @return array
*/
public function handle(ActionRequest $request, Action $exportable): array
{
$response = Excel::store(
$exportable,
$this->getFilename(),
$this->getDisk(),
$this->getWriterType()
);
if (false === $response) {
return \is_callable($this->onFailure)
? ($this->onFailure)($request, $response)
: Action::danger(__('Resource could not be exported.'));
}
return \is_callable($this->onSuccess)
? ($this->onSuccess)($request, $response)
: Action::message(__('Resource was successfully exported.'));
}
/**
* @param callable $callback
*
* @return $this
*/
public function onSuccess(callable $callback)
{
$this->onSuccess = $callback;
return $this;
}
/**
* @param callable $callback
*
* @return $this
*/
public function onFailure(callable $callback)
{
$this->onFailure = $callback;
return $this;
}
/**
* @param string $name
*
* @return $this
*/
public function withName(string $name)
{
$this->name = $name;
return $this;
}
/**
* @return Builder
*/
public function query()
{
return $this->query;
}
/**
* @return Field[]
*/
public function fields()
{
return $this->actionFields;
}
/**
* @param Model|mixed $row
*
* @return array
*/
public function map($row): array
{
$only = $this->getOnly();
$except = $this->getExcept();
if ($row instanceof Model) {
// If user didn't specify a custom except array, use the hidden columns.
// User can override this by passing an empty array ->except([])
// When user specifies with only(), ignore if the column is hidden or not.
if (!$this->onlyIndexFields && $except === null && (!is_array($only) || count($only) === 0)) {
$except = $row->getHidden();
}
// Make all attributes visible
$row->setHidden([]);
$row = $this->replaceFieldValuesWhenOnResource(
$row,
is_array($only) ? $only : array_keys($row->attributesToArray())
);
}
if (is_array($only) && count($only) > 0) {
$row = array_only($row, $only);
}
if (is_array($except) && count($except) > 0) {
$row = array_except($row, $except);
}
return $row;
}
/**
* @param Builder $query
*
* @return $this
*/
protected function withQuery($query)
{
$this->query = $query;
return $this;
}
/**
* @return string
*/
protected function getDefaultExtension(): string
{
return $this->getWriterType() ? strtolower($this->getWriterType()) : 'xlsx';
}
/**
* @param Model $model
* @param array $only
*
* @return array
*/
protected function replaceFieldValuesWhenOnResource(Model $model, array $only = []): array
{
$resource = $this->resolveResource($model);
$fields = $this->resourceFields($resource);
$row = [];
foreach ($fields as $field) {
if (!$this->isExportableField($field)) {
continue;
}
if (\in_array($field->attribute, $only, true)) {
$row[$field->attribute] = $field->value;
} elseif (\in_array($field->name, $only, true)) {
// When no field could be found by their attribute name, it's most likely a computed field.
$row[$field->name] = $field->value;
}
}
// Add fields that were requested by ->only(), but are not registered as fields in the Nova resource.
foreach (array_diff($only, array_keys($row)) as $attribute) {
if ($model->{$attribute}) {
$row[$attribute] = $model->{$attribute};
} else {
$row[$attribute] = '';
}
}
return $row;
}
/**
* @param \Laravel\Nova\Resource $resource
*
* @return Collection
*/
protected function resourceFields(Resource $resource)
{
return $this->request->resourceFields($resource);
}
/**
* @param Model $model
*
* @return \Laravel\Nova\Resource
*/
protected function resolveResource(Model $model): Resource
{
$resource = $this->resource;
return new $resource($model);
}
/**
* @param Field $field
*
* @return bool
*/
protected function isExportableField(Field $field): bool
{
return !$field instanceof Gravatar;
}
}