-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileUploader.php
54 lines (45 loc) · 1.6 KB
/
FileUploader.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
<?php
namespace App\Service;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\String\Slugger\SluggerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\Filesystem\Filesystem;
use App\Exception\FileUploadException;
class FileUploader
{
private $translator;
public function __construct(
private string $targetDirectory,
private SluggerInterface $slugger,
TranslatorInterface $translator
) {
$this->translator = $translator;
}
public function getTargetDirectory(): string
{
return $this->targetDirectory;
}
public function upload(UploadedFile $file): string
{
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$safeFilename = $this->slugger->slug($originalFilename);
$fileName = $safeFilename . '-' . uniqid() . '.' . $file->guessExtension();
try {
$file->move($this->getTargetDirectory(), $fileName);
} catch (FileException $e) {
throw new FileUploadException($this->translator->trans('errorUpload', [], 'errors'));
}
return $fileName;
}
public function remove($fileName): string
{
try {
$filesystem = new Filesystem();
$filesystem->remove([$this->getTargetDirectory() . '/' . $fileName]);
} catch (FileException $e) {
throw new FileException($this->translator->trans('error', [], 'errors'));
}
return 'success';
}
}