|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace ProjetNormandie\UserBundle\Service; |
|
4
|
|
|
|
|
5
|
|
|
use League\Flysystem\FilesystemException; |
|
6
|
|
|
use League\Flysystem\FilesystemOperator; |
|
7
|
|
|
use Symfony\Component\HttpFoundation\StreamedResponse; |
|
8
|
|
|
|
|
9
|
|
|
class AvatarManager |
|
10
|
|
|
{ |
|
11
|
|
|
private string $prefix = 'user/'; |
|
12
|
|
|
|
|
13
|
|
|
private array $extensions = array( |
|
14
|
|
|
'png' => 'image/png', |
|
15
|
|
|
'jpg' => 'image/jpeg' |
|
16
|
|
|
); |
|
17
|
|
|
|
|
18
|
|
|
private FilesystemOperator $appStorage; |
|
19
|
|
|
|
|
20
|
|
|
|
|
21
|
|
|
public function __construct(FilesystemOperator $appStorage) |
|
22
|
|
|
{ |
|
23
|
|
|
$this->appStorage = $appStorage; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* @throws FilesystemException |
|
28
|
|
|
*/ |
|
29
|
|
|
public function write(string $filename, string $contents) |
|
30
|
|
|
{ |
|
31
|
|
|
$this->appStorage->write($this->prefix . $filename, $contents); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* @throws FilesystemException |
|
37
|
|
|
*/ |
|
38
|
|
|
public function read(string $filename): StreamedResponse |
|
39
|
|
|
{ |
|
40
|
|
|
$path = $this->prefix . $filename; |
|
41
|
|
|
if (!$this->appStorage->fileExists($path)) { |
|
42
|
|
|
$path = $this->prefix . 'default.png'; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
$stream = $this->appStorage->readStream($path); |
|
46
|
|
|
return new StreamedResponse(function () use ($stream) { |
|
47
|
|
|
fpassthru($stream); |
|
48
|
|
|
exit(); |
|
|
|
|
|
|
49
|
|
|
}, 200, ['Content-Type' => $this->getMimeType($path)]); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
|
|
53
|
|
|
public function getAllowedMimeType(): array |
|
54
|
|
|
{ |
|
55
|
|
|
return array_values($this->extensions); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
public function getExtension($mimeType): string |
|
59
|
|
|
{ |
|
60
|
|
|
$types = array_flip($this->extensions); |
|
61
|
|
|
return $types[$mimeType] ?? 'png'; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
private function getMimeType(string $file): string |
|
65
|
|
|
{ |
|
66
|
|
|
$infos = pathinfo($file); |
|
67
|
|
|
return $this->extensions[$infos['extension']] ?? 'image/png'; |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|
In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.