Completed
Pull Request — master (#395)
by Anton
05:38
created

AttachmentResponse   A

Complexity

Total Complexity 1

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
dl 0
loc 34
ccs 0
cts 16
cp 0
rs 10
c 0
b 0
f 0
wmc 1
lcom 0
cbo 3

1 Method

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 18 1
1
<?php
2
/**
3
 * Bluz Framework Component
4
 *
5
 * @copyright Bluz PHP Team
6
 * @link https://github.com/bluzphp/framework
7
 */
8
9
declare(strict_types=1);
10
11
namespace Bluz\Response;
12
13
use Zend\Diactoros\Response as DiactorsResponse;
14
use Zend\Diactoros\Response\InjectContentTypeTrait;
15
use Zend\Diactoros\Stream;
16
17
/**
18
 * Class AttachmentResponse
19
 *
20
 * @package Bluz\Response
21
 * @link http://www.marco-bunge.com/2016/09/01/file-downloads-with-zend-diactoros/
22
 */
23
class AttachmentResponse extends DiactorsResponse
24
{
25
    use InjectContentTypeTrait;
26
27
    /**
28
     * Create a file attachment response.
29
     *
30
     * Produces a text response with a Content-Type of given file mime type and a default
31
     * status of 200.
32
     *
33
     * @param string $file Valid file path
34
     * @param int $status Integer status code for the response; 200 by default.
35
     * @param array $headers Array of headers to use at initialization.
36
     * @internal param StreamInterface|string $text String or stream for the message body.
37
     */
38
    public function __construct($file, $status = 200, array $headers = [])
39
    {
40
        $fileInfo = new \SplFileInfo($file);
41
42
        $headers = array_replace(
43
            $headers,
44
            [
45
                'content-length' => $fileInfo->getSize(),
46
                'content-disposition' => sprintf('attachment; filename=%s', $fileInfo->getFilename()),
47
            ]
48
        );
49
50
        parent::__construct(
51
            new Stream($fileInfo->getRealPath(), 'r'),
52
            $status,
53
            $this->injectContentType((new \finfo(FILEINFO_MIME_TYPE))->file($fileInfo->getRealPath()), $headers)
54
        );
55
    }
56
}
57