1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ProtoneMedia\LaravelMixins\Request; |
4
|
|
|
|
5
|
|
|
use Illuminate\Http\UploadedFile; |
6
|
|
|
use Illuminate\Support\Arr; |
7
|
|
|
use Illuminate\Support\Collection; |
8
|
|
|
use Illuminate\Support\Str; |
9
|
|
|
use Symfony\Component\HttpFoundation\FileBag; |
10
|
|
|
use Symfony\Component\HttpFoundation\ParameterBag; |
11
|
|
|
|
12
|
|
|
trait ConvertsBase64ToFiles |
13
|
|
|
{ |
14
|
|
|
protected function base64FileKeys(): array |
15
|
|
|
{ |
16
|
|
|
return []; |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Helper method to get the body parameters bag. |
21
|
|
|
* |
22
|
|
|
* @return \Symfony\Component\HttpFoundation\ParameterBag |
23
|
|
|
*/ |
24
|
|
|
private function bodyParametersBag(): ParameterBag |
25
|
|
|
{ |
26
|
|
|
return $this->request; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Helper method to get the uploaded files bag. |
31
|
|
|
* |
32
|
|
|
* @return FileBag |
33
|
|
|
*/ |
34
|
|
|
private function uploadFilesBag(): FileBag |
35
|
|
|
{ |
36
|
|
|
return $this->files; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Pulls the Base64 contents for each image key and creates |
41
|
|
|
* an UploadedFile instance from it and sets it on the |
42
|
|
|
* request. |
43
|
|
|
* |
44
|
|
|
* @return void |
45
|
|
|
*/ |
46
|
|
|
protected function prepareForValidation() |
47
|
|
|
{ |
48
|
|
|
$flattened = Arr::dot($this->base64FileKeys()); |
49
|
|
|
|
50
|
|
|
Collection::make($flattened)->each(function ($filename, $key) { |
51
|
|
|
rescue(function () use ($key, $filename) { |
52
|
|
|
$base64Contents = $this->input($key); |
|
|
|
|
53
|
|
|
|
54
|
|
|
if (!$base64Contents) { |
55
|
|
|
return; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
// Generate a temporary path to store the Base64 contents |
59
|
|
|
$tempFilePath = tempnam(sys_get_temp_dir(), $filename); |
60
|
|
|
|
61
|
|
|
// Store the contents using a stream, or by decoding manually |
62
|
|
|
if (Str::startsWith($base64Contents, 'data:') && count(explode(',', $base64Contents)) > 1) { |
63
|
|
|
$source = fopen($base64Contents, 'r'); |
64
|
|
|
$destination = fopen($tempFilePath, 'w'); |
65
|
|
|
|
66
|
|
|
stream_copy_to_stream($source, $destination); |
67
|
|
|
|
68
|
|
|
fclose($source); |
69
|
|
|
fclose($destination); |
70
|
|
|
} else { |
71
|
|
|
file_put_contents($tempFilePath, base64_decode($base64Contents, true)); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
$uploadedFile = new UploadedFile($tempFilePath, $filename, null, null, true); |
75
|
|
|
|
76
|
|
|
$body = $this->bodyParametersBag()->all(); |
77
|
|
|
Arr::forget($body, $key); |
78
|
|
|
$this->bodyParametersBag()->replace($body); |
79
|
|
|
|
80
|
|
|
$files = $this->uploadFilesBag()->all(); |
81
|
|
|
Arr::set($files, $key, $uploadedFile); |
82
|
|
|
$this->uploadFilesBag()->replace($files); |
83
|
|
|
}, null, false); |
84
|
|
|
}); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|