|
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, $currentKey, $groupName, $fieldName) |
|
13
|
|
|
{ |
|
14
|
|
|
$modelFolder = $this->slug . DIRECTORY_SEPARATOR; |
|
|
|
|
|
|
15
|
|
|
$basePath = base_path(config('anavel-crud.uploads_path')); |
|
16
|
|
|
$modelPath = $basePath . $modelFolder; |
|
17
|
|
|
$skipNext = false; |
|
18
|
|
|
$requestValue = null; |
|
19
|
|
|
if (! empty($fields[$groupName][$currentKey + 1]) && $fields[$groupName][$currentKey + 1]->getName() === $fieldName . '__delete') { |
|
20
|
|
|
//We never want to save this field, it doesn't exist in the DB |
|
21
|
|
|
$skipNext = true; |
|
22
|
|
|
|
|
23
|
|
|
//If user wants to delete the existing file |
|
24
|
|
|
if (! empty($request->input("main.{$fieldName}__delete"))) { |
|
25
|
|
|
$adapter = new Local($basePath); |
|
26
|
|
|
$filesystem = new Filesystem($adapter); |
|
27
|
|
|
if ($filesystem->has($item->$fieldName)) { |
|
28
|
|
|
$filesystem->delete($item->$fieldName); |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
|
|
32
|
|
|
$item->setAttribute( |
|
33
|
|
|
$fieldName, |
|
34
|
|
|
null |
|
35
|
|
|
); |
|
36
|
|
|
return [ |
|
37
|
|
|
'skipNext' => $skipNext |
|
38
|
|
|
]; |
|
39
|
|
|
} |
|
40
|
|
|
} |
|
41
|
|
|
if ($request->hasFile($groupName .'.'.$fieldName)) { |
|
42
|
|
|
$fileName = uniqid() . '.' . $request->file($groupName .'.'.$fieldName)->getClientOriginalExtension(); |
|
43
|
|
|
|
|
44
|
|
|
|
|
45
|
|
|
$request->file($groupName .'.'.$fieldName)->move( |
|
46
|
|
|
$modelPath, |
|
47
|
|
|
$fileName |
|
48
|
|
|
); |
|
49
|
|
|
|
|
50
|
|
|
$requestValue = $modelFolder . $fileName; |
|
51
|
|
|
} elseif (! $request->file($groupName .'.'.$fieldName)->isValid()) { |
|
52
|
|
|
throw new \Exception($request->file($groupName .'.'.$fieldName)->getErrorMessage()); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
return [ |
|
56
|
|
|
'requestValue' => $requestValue, |
|
57
|
|
|
'skipNext' => $skipNext |
|
58
|
|
|
]; |
|
59
|
|
|
} |
|
60
|
|
|
} |
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: