-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUploadFile.php
More file actions
81 lines (61 loc) · 1.84 KB
/
UploadFile.php
File metadata and controls
81 lines (61 loc) · 1.84 KB
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
<?php
namespace App\Service;
use Exception;
class UploadFile
{
private array $files = [];
private string $outputPath;
public function __construct(array $files, string $outputPath): static
{
$this->setOutputPath($outputPath);
$count = count($files['tmp_name']);
for ($i = 0; $i < $count; $i++) {
// sjdfkakfalsdf.jpg
// File type = image/jpeg => ['image', 'jpeg']
$fileType = explode('/', $files['type'][$i]);
$extension = end($fileType);
// 16cd019896f19fc76b6905bd13c3f2de . $extension
$name = '/' . md5($files['name'][$i] . random_bytes(64)) . '.' . $extension;
$this->files[] = [
'name' => $name,
'location' => $files['tmp_name'][$i],
];
}
return $this;
}
/**
* Set output path
*/
public function setOutputPath(string $path): static
{
$this->outputPath = $path;
return $this;
}
/**
* Save the uploaded files to disk
*/
public function save(string $path = ''): array
{
// create directory if doesn't exist.
$this->createDirectory($path);
$uploaded = [];
foreach ($this->files as $file) {
$finalPathWithName = $this->outputPath . $path . $file['name'];
move_uploaded_file($file['location'], $finalPathWithName);
$uploaded[] = $path . $file['name'];
}
return $uploaded;
}
public function createDirectory(string $path): bool
{
$location = $this->outputPath . $path;
try {
if (! file_exists($location)) {
mkdir($location);
return true;
}
} catch (\Exception) {
throw new Exception('Failed to create directory!');
}
}
}