Passed
Push — develop ( a62e64...ed3562 )
by BENARD
06:54 queued 02:34
created

AvatarManager::getExtension()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
namespace VideoGamesRecords\CoreBundle\Manager;
3
4
use League\Flysystem\FilesystemException;
5
use League\Flysystem\FilesystemOperator;
6
use Symfony\Component\HttpFoundation\StreamedResponse;
7
8
class AvatarManager
9
{
10
    private string $prefix = 'team/';
11
12
    private array $extensions = array(
13
        'png' => 'image/png',
14
        'jpg' => 'image/jpeg'
15
    );
16
17
    private FilesystemOperator $appStorage;
18
19
20
    public function __construct(FilesystemOperator $appStorage)
21
    {
22
        $this->appStorage = $appStorage;
23
    }
24
25
    /**
26
     * @throws FilesystemException
27
     */
28
    public function write(string $filename, string $contents): void
29
    {
30
        $this->appStorage->write($this->prefix . $filename, $contents);
31
    }
32
33
34
    /**
35
     * @param string|null $filename
36
     * @return StreamedResponse
37
     * @throws FilesystemException
38
     */
39
    public function read(?string $filename): StreamedResponse
40
    {
41
        $path = $this->prefix . $filename;
42
        if (!$this->appStorage->fileExists($path)) {
43
            $path = $this->prefix . 'default.png';
44
        }
45
46
        $stream = $this->appStorage->readStream($path);
47
        return new StreamedResponse(function() use ($stream) {
48
            fpassthru($stream);
49
            exit();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
50
        }, 200, ['Content-Type' => $this->getMimeType($path)]);
51
    }
52
53
54
    public function getAllowedMimeType(): array
55
    {
56
        return array_values($this->extensions);
57
    }
58
59
    public function getExtension($mimeType): string
60
    {
61
        $types = array_flip($this->extensions);
62
        return $types[$mimeType] ?? 'png';
63
    }
64
65
    private function getMimeType(string $file): string
66
    {
67
        $infos = pathinfo($file);
68
        return $this->extensions[$infos['extension']] ?? 'image/png';
69
    }
70
}
71