|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace League\Glide\Responses; |
|
4
|
|
|
|
|
5
|
|
|
use Closure; |
|
6
|
|
|
use League\Flysystem\FilesystemInterface; |
|
7
|
|
|
use League\Glide\Filesystem\FilesystemException; |
|
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
9
|
|
|
|
|
10
|
|
|
class PsrResponseFactory implements ResponseFactoryInterface |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* Base response object. |
|
14
|
|
|
* @var ResponseInterface |
|
15
|
|
|
*/ |
|
16
|
|
|
protected $response; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* Callback to create stream. |
|
20
|
|
|
* @var Closure |
|
21
|
|
|
*/ |
|
22
|
|
|
protected $streamCallback; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* Create PsrResponseFactory instance. |
|
26
|
|
|
* @param ResponseInterface $response Base response object. |
|
27
|
|
|
* @param Closure $streamCallback Callback to create stream. |
|
28
|
|
|
*/ |
|
29
|
|
|
public function __construct(ResponseInterface $response, Closure $streamCallback) |
|
30
|
|
|
{ |
|
31
|
|
|
$this->response = $response; |
|
32
|
|
|
$this->streamCallback = $streamCallback; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* Create response. |
|
37
|
|
|
* @param FilesystemInterface $cache Cache file system. |
|
38
|
|
|
* @param string $path Cached file path. |
|
39
|
|
|
* @return ResponseInterface Response object. |
|
40
|
|
|
*/ |
|
41
|
|
|
public function create(FilesystemInterface $cache, $path) |
|
42
|
|
|
{ |
|
43
|
|
|
$stream = $this->streamCallback->__invoke( |
|
44
|
|
|
$cache->readStream($path) |
|
45
|
|
|
); |
|
46
|
|
|
|
|
47
|
|
|
$contentType = $cache->getMimetype($path); |
|
48
|
|
|
$contentLength = (string) $cache->getSize($path); |
|
49
|
|
|
$cacheControl = 'max-age=31536000, public'; |
|
50
|
|
|
$expires = date_create('+1 years')->format('D, d M Y H:i:s').' GMT'; |
|
51
|
|
|
|
|
52
|
|
|
if ($contentType === false) { |
|
53
|
|
|
throw new FilesystemException('Unable to determine the image content type.'); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
if ($contentLength === false) { |
|
57
|
|
|
throw new FilesystemException('Unable to determine the image content length.'); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
return $this->response->withBody($stream) |
|
61
|
|
|
->withHeader('Content-Type', $contentType) |
|
62
|
|
|
->withHeader('Content-Length', $contentLength) |
|
63
|
|
|
->withHeader('Cache-Control', $cacheControl) |
|
64
|
|
|
->withHeader('Expires', $expires); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|