|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Odiseo\BlogBundle\Uploader; |
|
6
|
|
|
|
|
7
|
|
|
use Gaufrette\Filesystem; |
|
8
|
|
|
use Odiseo\BlogBundle\Model\ImageInterface; |
|
9
|
|
|
use Symfony\Component\HttpFoundation\File\File; |
|
10
|
|
|
use Webmozart\Assert\Assert; |
|
11
|
|
|
|
|
12
|
|
|
class ImageUploader implements ImageUploaderInterface |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* @var Filesystem |
|
16
|
|
|
*/ |
|
17
|
|
|
protected $filesystem; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @param Filesystem $filesystem |
|
21
|
|
|
*/ |
|
22
|
|
|
public function __construct(Filesystem $filesystem) |
|
23
|
|
|
{ |
|
24
|
|
|
$this->filesystem = $filesystem; |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* {@inheritdoc} |
|
29
|
|
|
*/ |
|
30
|
|
|
public function upload(ImageInterface $image): void |
|
31
|
|
|
{ |
|
32
|
|
|
if (!$image->hasFile()) { |
|
33
|
|
|
return; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
$file = $image->getFile(); |
|
37
|
|
|
|
|
38
|
|
|
/** @var File $file */ |
|
39
|
|
|
Assert::isInstanceOf($file, File::class); |
|
40
|
|
|
|
|
41
|
|
|
if (null !== $image->getPath() && $this->has($image->getPath())) { |
|
42
|
|
|
$this->remove($image->getPath()); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
do { |
|
46
|
|
|
$hash = bin2hex(random_bytes(16)); |
|
47
|
|
|
$path = $this->expandPath($hash . '.' . $file->guessExtension()); |
|
48
|
|
|
} while ($this->filesystem->has($path)); |
|
49
|
|
|
|
|
50
|
|
|
$image->setPath($path); |
|
51
|
|
|
|
|
52
|
|
|
/** @var \SplFileInfo $file */ |
|
53
|
|
|
$file = $image->getFile(); |
|
54
|
|
|
/** @var string $fileContents */ |
|
55
|
|
|
$fileContents = file_get_contents($file->getPathname()); |
|
56
|
|
|
$this->filesystem->write( |
|
57
|
|
|
$image->getPath(), |
|
58
|
|
|
$fileContents |
|
59
|
|
|
); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
/** |
|
63
|
|
|
* {@inheritdoc} |
|
64
|
|
|
*/ |
|
65
|
|
|
public function remove(string $path): bool |
|
66
|
|
|
{ |
|
67
|
|
|
if ($this->filesystem->has($path)) { |
|
68
|
|
|
return $this->filesystem->delete($path); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
return false; |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
/** |
|
75
|
|
|
* @param string $path |
|
76
|
|
|
* |
|
77
|
|
|
* @return string |
|
78
|
|
|
*/ |
|
79
|
|
|
private function expandPath(string $path): string |
|
80
|
|
|
{ |
|
81
|
|
|
return sprintf( |
|
82
|
|
|
'%s/%s/%s', |
|
83
|
|
|
substr($path, 0, 2), |
|
84
|
|
|
substr($path, 2, 2), |
|
85
|
|
|
substr($path, 4) |
|
86
|
|
|
); |
|
87
|
|
|
} |
|
88
|
|
|
|
|
89
|
|
|
/** |
|
90
|
|
|
* @param string $path |
|
91
|
|
|
* |
|
92
|
|
|
* @return bool |
|
93
|
|
|
*/ |
|
94
|
|
|
private function has(string $path): bool |
|
95
|
|
|
{ |
|
96
|
|
|
return $this->filesystem->has($path); |
|
97
|
|
|
} |
|
98
|
|
|
} |
|
99
|
|
|
|