Completed
Push — master ( e60207...37fe77 )
by Jonathan
05:38
created

PsrResponseFactory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
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 6
    public function __construct(ResponseInterface $response, Closure $streamCallback)
30
    {
31 6
        $this->response = $response;
32 6
        $this->streamCallback = $streamCallback;
33 6
    }
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 3
    public function create(FilesystemInterface $cache, $path)
42
    {
43 3
        $stream = $this->streamCallback->__invoke(
44 3
            $cache->readStream($path)
45 3
        );
46
47 3
        $contentType = $cache->getMimetype($path);
48 3
        $contentLength = (string) $cache->getSize($path);
49 3
        $cacheControl = 'max-age=31536000, public';
50 3
        $expires = date_create('+1 years')->format('D, d M Y H:i:s').' GMT';
51
52 3
        if ($contentType === false) {
53
            throw new FilesystemException('Unable to determine the image content type.');
54
        }
55
56 3
        if ($contentLength === false) {
57
            throw new FilesystemException('Unable to determine the image content length.');
58
        }
59
60 3
        return $this->response->withBody($stream)
61 3
            ->withHeader('Content-Type', $contentType)
62 3
            ->withHeader('Content-Length', $contentLength)
63 3
            ->withHeader('Cache-Control', $cacheControl)
64 3
            ->withHeader('Expires', $expires);
65
    }
66
}
67