1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Obblm\Core\Helper\FileUploader; |
4
|
|
|
|
5
|
|
|
use Symfony\Component\Filesystem\Exception\IOExceptionInterface; |
6
|
|
|
use Symfony\Component\Filesystem\Filesystem; |
7
|
|
|
use Symfony\Component\HttpFoundation\File\Exception\FileException; |
8
|
|
|
use Symfony\Component\HttpFoundation\File\File; |
9
|
|
|
use Symfony\Component\HttpFoundation\File\UploadedFile; |
10
|
|
|
use Symfony\Component\String\Slugger\SluggerInterface; |
11
|
|
|
|
12
|
|
|
class AbstractFileUploader |
13
|
|
|
{ |
14
|
|
|
private $targetDirectory; |
15
|
|
|
private $uploadDirectory; |
16
|
|
|
private $slugger; |
17
|
|
|
|
18
|
|
|
public function __construct($targetDirectory, SluggerInterface $slugger) |
19
|
|
|
{ |
20
|
|
|
$this->targetDirectory = $targetDirectory; |
21
|
|
|
$this->uploadDirectory = $targetDirectory; |
22
|
|
|
$this->slugger = $slugger; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
public function removeOldFile(string $filename = '') |
26
|
|
|
{ |
27
|
|
|
$filesystem = new Filesystem(); |
28
|
|
|
|
29
|
|
|
try { |
30
|
|
|
$filesystem->remove($this->getObjectDirectory() . '/' . $filename); |
31
|
|
|
} catch (IOExceptionInterface $exception) { |
32
|
|
|
echo "An error occurred while creating your directory at ".$exception->getPath(); |
33
|
|
|
} |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public function getTargetDirectory(): ?string |
37
|
|
|
{ |
38
|
|
|
return $this->targetDirectory; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public function getObjectDirectory(): ?string |
42
|
|
|
{ |
43
|
|
|
return $this->uploadDirectory; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function setObjectSubDirectory(string $uploadDirectory): self |
47
|
|
|
{ |
48
|
|
|
$this->uploadDirectory = $this->targetDirectory .'/' . $uploadDirectory; |
49
|
|
|
return $this; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* @param UploadedFile $file |
54
|
|
|
* @return File|null |
55
|
|
|
*/ |
56
|
|
|
public function upload(UploadedFile $file):?File |
57
|
|
|
{ |
58
|
|
|
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME); |
59
|
|
|
$safeFilename = $this->slugger->slug($originalFilename); |
60
|
|
|
$fileName = $safeFilename.'-'.uniqid().'.'.$file->guessExtension(); |
61
|
|
|
|
62
|
|
|
try { |
63
|
|
|
$newFile = $file->move($this->getObjectDirectory(), $fileName); |
|
|
|
|
64
|
|
|
} catch (FileException $e) { |
65
|
|
|
return null; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
return $newFile; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|