-
-
Notifications
You must be signed in to change notification settings - Fork 659
/
Copy pathAttachmentController.php
113 lines (92 loc) · 2.77 KB
/
AttachmentController.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
<?php
declare(strict_types=1);
namespace Orchid\Platform\Http\Controllers;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Orchid\Attachment\File;
use Orchid\Attachment\Models\Attachment;
use Orchid\Platform\Dashboard;
use Orchid\Platform\Events\UploadedFileEvent;
use Symfony\Component\HttpFoundation\Response;
/**
* Class AttachmentController.
*/
class AttachmentController extends Controller
{
/**
* @var Attachment
*/
protected $attachment;
/**
* AttachmentController constructor.
*/
public function __construct()
{
$this->checkPermission('platform.systems.attachment');
$this->attachment = Dashboard::modelClass(Attachment::class);
}
public function upload(Request $request): JsonResponse
{
$attachment = collect($request->allFiles())
->flatten()
->map(fn (UploadedFile $file) => $this->createModel($file, $request));
$response = $attachment->count() > 1 ? $attachment : $attachment->first();
return response()->json($response);
}
public function sort(Request $request): void
{
collect($request->get('files', []))
->each(function ($sort, $id) {
$attachment = $this->attachment->find($id);
$attachment->sort = $sort;
$attachment->save();
});
}
/**
* Delete files.
*/
public function destroy(string $id, Request $request): void
{
$storage = $request->get('storage', 'public');
$this->attachment->findOrFail($id)->delete($storage);
}
/**
* @return ResponseFactory|Response
*/
public function update(string $id, Request $request)
{
$attachment = $this->attachment
->findOrFail($id)
->fill($request->all());
$attachment->save();
return response()->json($attachment);
}
/**
* @throws BindingResolutionException
*
* @return mixed
*/
private function createModel(UploadedFile $file, Request $request)
{
$file = resolve(File::class, [
'file' => $file,
'disk' => $request->get('storage'),
'group' => $request->get('group'),
]);
if ($request->has('path')) {
$file->path($request->get('path'));
}
$model = $file->load();
$model->url = $model->url();
event(new UploadedFileEvent($model));
return $model;
}
public function media(): JsonResponse
{
$attachments = $this->attachment->filters()->paginate(12);
return response()->json($attachments);
}
}