Skip to content
This repository was archived by the owner on Jan 29, 2020. It is now read-only.

Commit 1232e66

Browse files
committed
Add a trait for managing download responses
After doing a bit of searching, I didn't find anything that would help with sending a downloaded response, instead of the default, which is to send a text response. So I created this one, which sends six headers that ensure that the response sent will be interpreted by the client as a downloadable file.
1 parent 42841b2 commit 1232e66

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
<?php
2+
/**
3+
* @see https://github.com/zendframework/zend-diactoros for the canonical source repository
4+
* @copyright Copyright (c) 2015-2018 Zend Technologies USA Inc. (https://www.zend.com)
5+
* @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License
6+
*/
7+
8+
declare(strict_types=1);
9+
10+
namespace Zend\Diactoros\Response;
11+
12+
use Zend\Diactoros\Exception\InvalidArgumentException;
13+
14+
use function array_keys;
15+
use function array_merge;
16+
use function implode;
17+
use function in_array;
18+
use function sprintf;
19+
20+
/**
21+
* Trait DownloadResponseTrait
22+
* @package Zend\Diactoros\Response
23+
*/
24+
trait DownloadResponseTrait
25+
{
26+
/**
27+
* A list of header keys required to be sent with a download response
28+
*
29+
* @var array
30+
*/
31+
private $downloadResponseHeaders = [
32+
'cache-control',
33+
'content-description',
34+
'content-disposition',
35+
'content-transfer-encoding',
36+
'expires',
37+
'pragma'
38+
];
39+
40+
/**
41+
* Check if the extra headers contain any of the download headers
42+
*
43+
* The download headers cannot be overridden.
44+
*
45+
* @param array $downloadHeaders
46+
* @param array $headers
47+
* @return bool
48+
*/
49+
public function overridesDownloadHeaders(array $downloadHeaders, array $headers = []) : bool
50+
{
51+
$overridesDownloadHeaders = false;
52+
53+
foreach (array_keys($headers) as $header) {
54+
if (in_array($header, $downloadHeaders)) {
55+
$overridesDownloadHeaders = true;
56+
break;
57+
}
58+
}
59+
60+
return $overridesDownloadHeaders;
61+
}
62+
63+
/**
64+
* Prepare download response headers
65+
*
66+
* @param string $filename
67+
* @param array $headers
68+
* @return array
69+
*/
70+
private function prepareDownloadHeaders(string $filename, array $headers = []) : array
71+
{
72+
if ($this->overridesDownloadHeaders($this->downloadResponseHeaders, $headers)) {
73+
throw new InvalidArgumentException(
74+
sprintf(
75+
'Cannot override download headers (%s) when download response is being sent',
76+
implode(', ', $this->downloadResponseHeaders)
77+
)
78+
);
79+
}
80+
81+
return array_merge($headers, $this->getDownloadHeaders($filename));
82+
}
83+
}

0 commit comments

Comments
 (0)