Passed
Push — main ( ab47dd...702890 )
by Daniel
12:30
created

CachedArtResponseProvider::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 0
nc 1
nop 3
dl 0
loc 5
ccs 1
cts 1
cp 1
crap 1
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace Uxmp\Core\Component\Art;
4
5
use Nyholm\Psr7\Factory\Psr17Factory;
6
use Psr\Http\Message\ResponseInterface;
7
use Slim\HttpCache\CacheProvider;
8
use Uxmp\Core\Component\Config\ConfigProviderInterface;
9
10
final class CachedArtResponseProvider implements CachedArtResponseProviderInterface
11
{
12 3
    public function __construct(
13
        private CacheProvider $cacheProvider,
14
        private ConfigProviderInterface $config,
15
        private Psr17Factory $psr17Factory,
16
    ) {
17 3
    }
18
19 3
    public function withCachedArt(
20
        ResponseInterface $response,
21
        CachableArtItemInterface $item,
22
    ): ResponseInterface {
23 3
        $artItemId = $item->getArtItemId();
24
25 3
        if ($artItemId === null) {
26 1
            return $this->createErrorResponse($response);
27
        }
28
29 2
        $filename = $artItemId . '.jpg';
30 2
        $path = sprintf(
31 2
            '%s/%s',
32 2
            $this->config->getAssetPath() . '/img/' . $item->getArtItemType(),
33
            $filename
34
        );
35 2
        $mimeType = 'image/jpg';
36
37 2
        if (!file_exists($path)) {
38 1
            return $this->createErrorResponse($response);
39
        }
40
41 1
        return $this->createResponse(
42 1
            $response,
43
            $path,
44
            $mimeType,
45
            $filename,
46 1
            $item->getLastModified()?->getTimestamp()
47
        );
48
    }
49
50 2
    private function createErrorResponse(
51
        ResponseInterface $response
52
    ): ResponseInterface {
53 2
        return $this->createResponse(
54 2
            $response,
55 2
            (string) realpath(__DIR__ . '/../../../resource/asset/disc.png'),
56 2
            'image/png',
57 2
            'disc.png'
58
        );
59
    }
60
61 3
    private function createResponse(
62
        ResponseInterface $response,
63
        string $path,
64
        string $mimeType,
65
        string $filename,
66
        ?int $lastModified = null
67
    ): ResponseInterface {
68 3
        return $this->cacheProvider
69 3
            ->withEtag($response, md5((string) $lastModified))
70 3
            ->withHeader('Content-Type', $mimeType)
71 3
            ->withHeader('Content-Disposition', 'filename='.$filename)
72 3
            ->withBody(
73 3
                $this->psr17Factory->createStreamFromFile($path)
74
            );
75
    }
76
}
77