1 | <?php |
||
21 | class ImageUploader implements ImageUploaderInterface |
||
22 | { |
||
23 | /** |
||
24 | * @var Filesystem |
||
25 | */ |
||
26 | protected $filesystem; |
||
27 | |||
28 | /** |
||
29 | * @param Filesystem $filesystem |
||
30 | */ |
||
31 | public function __construct(Filesystem $filesystem) |
||
35 | |||
36 | /** |
||
37 | * {@inheritdoc} |
||
38 | */ |
||
39 | public function upload(ImageInterface $image): void |
||
40 | { |
||
41 | if (!$image->hasFile()) { |
||
42 | return; |
||
43 | } |
||
44 | |||
45 | $file = $image->getFile(); |
||
46 | |||
47 | /** @var File $file */ |
||
48 | Assert::isInstanceOf($file, File::class); |
||
49 | |||
50 | if (null !== $image->getPath() && $this->has($image->getPath())) { |
||
51 | $this->remove($image->getPath()); |
||
52 | } |
||
53 | |||
54 | do { |
||
55 | $hash = bin2hex(random_bytes(16)); |
||
56 | $path = $this->expandPath($hash . '.' . $file->guessExtension()); |
||
57 | } while ($this->isAdBlockingProne($path) || $this->filesystem->has($path)); |
||
58 | |||
59 | $image->setPath($path); |
||
60 | |||
61 | $this->filesystem->write( |
||
62 | $image->getPath(), |
||
63 | file_get_contents($image->getFile()->getPathname()) |
||
64 | ); |
||
65 | } |
||
66 | |||
67 | /** |
||
68 | * {@inheritdoc} |
||
69 | */ |
||
70 | public function remove(string $path): bool |
||
78 | |||
79 | /** |
||
80 | * @param string $path |
||
81 | * |
||
82 | * @return string |
||
83 | */ |
||
84 | private function expandPath(string $path): string |
||
93 | |||
94 | /** |
||
95 | * @param string $path |
||
96 | * |
||
97 | * @return bool |
||
98 | */ |
||
99 | private function has(string $path): bool |
||
103 | |||
104 | /** |
||
105 | * Will return true if the path is prone to be blocked by ad blockers |
||
106 | * |
||
107 | * @param string $path |
||
108 | * |
||
109 | * @return bool |
||
110 | */ |
||
111 | private function isAdBlockingProne(string $path): bool |
||
115 | } |
||
116 |