|
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
|
|
|
|