1
|
|
|
<?php |
2
|
|
|
namespace Staticus\Diactoros\Response; |
3
|
|
|
|
4
|
|
|
use Psr\Http\Message\StreamInterface; |
5
|
|
|
use Zend\Diactoros\Response; |
6
|
|
|
use Zend\Diactoros\Stream; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* A class representing HTTP responses with body. |
10
|
|
|
*/ |
11
|
|
|
class FileContentResponse extends Response implements FileResponseInterface |
12
|
|
|
{ |
13
|
|
|
use Response\InjectContentTypeTrait; |
14
|
|
|
/** |
15
|
|
|
* @var resource |
16
|
|
|
*/ |
17
|
|
|
protected $resource; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var string |
21
|
|
|
*/ |
22
|
|
|
protected $content; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @return resource |
26
|
|
|
*/ |
27
|
|
|
public function getResource() |
28
|
|
|
{ |
29
|
|
|
return $this->resource; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @return string |
34
|
|
|
*/ |
35
|
|
|
public function getContent() |
36
|
|
|
{ |
37
|
|
|
return $this->content; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param mixed $content |
42
|
|
|
*/ |
43
|
|
|
public function setContent($content) |
44
|
|
|
{ |
45
|
|
|
$this->content = $content; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Create an empty response with the given status code. |
50
|
|
|
* |
51
|
|
|
* @param string|resource|Stream $content |
52
|
|
|
* @param int $status Status code for the response, if any. |
53
|
|
|
* @param array $headers Headers for the response, if any. |
54
|
|
|
*/ |
55
|
|
|
public function __construct($content = null, $status = 204, array $headers = []) |
56
|
|
|
{ |
57
|
|
|
$body = $this->createBody($content); |
58
|
|
|
parent::__construct($body, $status, $headers); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
protected function createBody($content) |
62
|
|
|
{ |
63
|
|
|
if (is_resource($content)) { |
64
|
|
|
$this->resource = $content; |
65
|
|
|
$content = null; |
66
|
|
|
} |
67
|
|
|
$this->content = $content; |
68
|
|
|
if ($content instanceof StreamInterface) { |
69
|
|
|
|
70
|
|
|
return $content; |
71
|
|
|
} elseif (null === $content || false === $content || '' === $content) { // but not zero |
72
|
|
|
$stream = new Stream('php://temp', 'r'); |
73
|
|
|
|
74
|
|
|
return $stream; |
75
|
|
|
} |
76
|
|
|
$stream = new Stream('php://temp', 'wb+'); |
77
|
|
|
$stream->write((string)$content); |
78
|
|
|
$stream->rewind(); |
79
|
|
|
|
80
|
|
|
return $stream; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|