This repository was archived by the owner on Jan 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathCsvResponse.php
More file actions
84 lines (74 loc) · 2.53 KB
/
Copy pathCsvResponse.php
File metadata and controls
84 lines (74 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
/**
* @see https://github.com/zendframework/zend-diactoros for the canonical source repository
* @copyright Copyright (c) 2019 Zend Technologies USA Inc. (https://www.zend.com)
* @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License
*/
declare(strict_types=1);
namespace Zend\Diactoros\Response;
use Psr\Http\Message\StreamInterface;
use Zend\Diactoros\Exception;
use Zend\Diactoros\Response;
use Zend\Diactoros\Stream;
use function get_class;
use function gettype;
use function is_object;
use function is_string;
use function sprintf;
/**
* CSV response.
*
* Allows creating a CSV response by passing a string to the constructor;
* by default, sets a status code of 200 and sets the Content-Type header to
* text/csv.
*/
class CsvResponse extends Response
{
use InjectContentTypeTrait;
/**
* Create a CSV response.
*
* Produces a CSV response with a Content-Type of text/csv and a default
* status of 200.
*
* @param string|StreamInterface $text String or stream for the message body.
* @param int $status Integer status code for the response; 200 by default.
* @param string $filename
* @param array $headers Array of headers to use at initialization.
*/
public function __construct($text, int $status = 200, string $filename = '', array $headers = [])
{
if (is_string($filename) && $filename !== '') {
$headers = $this->prepareDownloadHeaders($filename, $headers);
}
parent::__construct(
$this->createBody($text),
$status,
$this->injectContentType('text/csv; charset=utf-8', $headers)
);
}
/**
* Create the CSV message body.
*
* @param string|StreamInterface $text
* @return StreamInterface
* @throws Exception\InvalidArgumentException if $text is neither a string or stream.
*/
private function createBody($text) : StreamInterface
{
if ($text instanceof StreamInterface) {
return $text;
}
if (! is_string($text)) {
throw new Exception\InvalidArgumentException(sprintf(
'Invalid CSV content (%s) provided to %s',
(is_object($text) ? get_class($text) : gettype($text)),
__CLASS__
));
}
$body = new Stream('php://temp', 'wb+');
$body->write($text);
$body->rewind();
return $body;
}
}