Completed
Push — master ( 4f4fb1...2bb66e )
by Jonathan
02:15
created

PsrResponseFactory::create()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 3.0146

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 25
ccs 15
cts 17
cp 0.8824
rs 8.8571
cc 3
eloc 16
nc 3
nop 2
crap 3.0146
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 2
        );
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