1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
|
4
|
|
|
namespace Anavel\Crud\Abstractor\Eloquent\Traits; |
5
|
|
|
|
6
|
|
|
use League\Flysystem\Adapter\Local; |
7
|
|
|
use League\Flysystem\Filesystem; |
8
|
|
|
use Illuminate\Http\Request; |
9
|
|
|
|
10
|
|
|
trait HandleFiles |
11
|
|
|
{ |
12
|
|
|
protected function handleField(Request $request, $item, array $fields, $groupName, $fieldName) |
13
|
|
|
{ |
14
|
|
|
$modelFolder = $this->slug . DIRECTORY_SEPARATOR; |
|
|
|
|
15
|
|
|
$basePath = base_path(DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR .config('anavel-crud.uploads_path')); |
16
|
|
|
$modelPath = $basePath . $modelFolder; |
17
|
|
|
$skip = null; |
18
|
|
|
$requestValue = null; |
19
|
|
|
if (! empty($fields["{$fieldName}__delete"])) { |
20
|
|
|
//We never want to save this field, it doesn't exist in the DB |
21
|
|
|
$skip = "{$fieldName}__delete"; |
22
|
|
|
|
23
|
|
|
|
24
|
|
|
//If user wants to delete the existing file |
25
|
|
|
if (! empty($request->input("{$groupName}.{$fieldName}__delete"))) { |
26
|
|
|
$adapter = new Local($basePath); |
27
|
|
|
$filesystem = new Filesystem($adapter); |
28
|
|
|
if ($filesystem->has($item->$fieldName)) { |
29
|
|
|
$filesystem->delete($item->$fieldName); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
|
33
|
|
|
$item->setAttribute( |
34
|
|
|
$fieldName, |
35
|
|
|
null |
36
|
|
|
); |
37
|
|
|
return [ |
38
|
|
|
'skip' => $skip |
39
|
|
|
]; |
40
|
|
|
} |
41
|
|
|
} |
42
|
|
|
if ($request->hasFile($groupName .'.'.$fieldName)) { |
43
|
|
|
$fileName = pathinfo($request->file($groupName .'.'.$fieldName)->getClientOriginalName(), PATHINFO_FILENAME); |
44
|
|
|
$extension = pathinfo($request->file($groupName .'.'.$fieldName)->getClientOriginalName(), PATHINFO_EXTENSION); |
45
|
|
|
|
46
|
|
|
$fileName = uniqid() . '_' . slugify($fileName); |
47
|
|
|
if (! empty($extension)) { |
48
|
|
|
$fileName .= '.' . $extension; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
|
52
|
|
|
$request->file($groupName .'.'.$fieldName)->move( |
53
|
|
|
$modelPath, |
54
|
|
|
$fileName |
55
|
|
|
); |
56
|
|
|
|
57
|
|
|
$requestValue = $modelFolder . $fileName; |
58
|
|
|
} elseif (! empty($request->file($groupName .'.'.$fieldName)) && ! $request->file($groupName .'.'.$fieldName)->isValid()) { |
59
|
|
|
throw new \Exception($request->file($groupName .'.'.$fieldName)->getErrorMessage()); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
//Avoid losing the existing filename if the user doesn't change it: |
63
|
|
|
if (empty($requestValue) && (! empty($item->$fieldName))) { |
64
|
|
|
$requestValue = $item->$fieldName; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
return [ |
68
|
|
|
'requestValue' => $requestValue, |
69
|
|
|
'skip' => $skip |
70
|
|
|
]; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: