-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathExportOperation.php
92 lines (79 loc) · 2.65 KB
/
ExportOperation.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
<?php
namespace Jargoud\LaravelBackpackExport\Http\Controllers\Operations;
use Backpack\CRUD\app\Library\CrudPanel\CrudPanelFacade as CRUD;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Support\Facades\Route;
use Jargoud\LaravelBackpackExport\Excel\Excel;
use Jargoud\LaravelBackpackExport\Excel\Writer;
use Jargoud\LaravelBackpackExport\Exportable;
use Jargoud\LaravelBackpackExport\Providers\LaravelBackpackExportServiceProvider as ServiceProviderAlias;
use Maatwebsite\Excel\Files\Filesystem;
use Maatwebsite\Excel\QueuedWriter;
use Maatwebsite\Excel\Reader;
use Symfony\Component\HttpFoundation\StreamedResponse;
trait ExportOperation
{
/**
* @return StreamedResponse
* @throws BindingResolutionException
*/
public function export(): StreamedResponse
{
$app = app();
$excel = new Excel(
$app->make(Writer::class),
$app->make(QueuedWriter::class),
$app->make(Reader::class),
$app->make(Filesystem::class)
);
return $excel->download(
$this->getExportClass(),
$this->getExportName(),
$this->getExportType()
);
}
abstract protected function getExportClass();
protected function getExportName(): string
{
return sprintf(
'%s-%s.%s',
now()->format('YmdHis'),
CRUD::getModel()->getTable(),
strtolower($this->getExportType())
);
}
protected function getExportType(): ?string
{
return null;
}
/**
* Define which routes are needed for this operation.
*
* @param string $segment Name of the current entity (singular). Used as first URL segment.
* @param string $routeName Prefix of the route name.
* @param string $controller Name of the current CrudController.
*/
protected function setupOperationRoutes(string $segment, string $routeName, string $controller): void
{
Route::get($segment . '/export', [
'as' => $routeName . '.export',
'uses' => $controller . '@export',
'operation' => 'export',
]);
}
/**
* Add the default settings, buttons, etc that this operation needs.
*/
protected function setupExportDefaults(): void
{
CRUD::allowAccess('export');
CRUD::operation('export', function (): void {
CRUD::loadDefaultOperationSettingsFromConfig();
});
}
protected function addExportButton(string $stack = 'top'): self
{
CRUD::addButton($stack, 'export', 'view', ServiceProviderAlias::NAMESPACE . '::buttons.export');
return $this;
}
}