AvatarManager::read()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 12
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace VideoGamesRecords\CoreBundle\Manager;
6
7
use League\Flysystem\FilesystemException;
8
use League\Flysystem\FilesystemOperator;
9
use Symfony\Component\HttpFoundation\StreamedResponse;
10
11
class AvatarManager
12
{
13
    private string $prefix = 'team/';
14
15
    private array $extensions = array(
16
        'png' => 'image/png',
17
        'jpg' => 'image/jpeg'
18
    );
19
20
    private FilesystemOperator $appStorage;
21
22
    public function __construct(FilesystemOperator $appStorage)
23
    {
24
        $this->appStorage = $appStorage;
25
    }
26
27
    /**
28
     * @throws FilesystemException
29
     */
30
    public function write(string $filename, string $contents): void
31
    {
32
        $this->appStorage->write($this->prefix . $filename, $contents);
33
    }
34
35
36
    /**
37
     * @param string|null $filename
38
     * @return StreamedResponse
39
     * @throws FilesystemException
40
     */
41
    public function read(?string $filename): StreamedResponse
42
    {
43
        $path = $this->prefix . $filename;
44
        if (!$this->appStorage->fileExists($path)) {
45
            $path = $this->prefix . 'default.png';
46
        }
47
48
        $stream = $this->appStorage->readStream($path);
49
        return new StreamedResponse(function () use ($stream) {
50
            fpassthru($stream);
51
            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...
52
        }, 200, ['Content-Type' => $this->getMimeType($path)]);
53
    }
54
55
56
    public function getAllowedMimeType(): array
57
    {
58
        return array_values($this->extensions);
59
    }
60
61
    public function getExtension($mimeType): string
62
    {
63
        $types = array_flip($this->extensions);
64
        return $types[$mimeType] ?? 'png';
65
    }
66
67
    private function getMimeType(string $file): string
68
    {
69
        $infos = pathinfo($file);
70
        return $this->extensions[$infos['extension']] ?? 'image/png';
71
    }
72
}
73