|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Bone\Http\Response; |
|
4
|
|
|
|
|
5
|
|
|
use Bone\Http\Response; |
|
6
|
|
|
use Bone\Server\Traits\HasAttributesTrait; |
|
7
|
|
|
use InvalidArgumentException; |
|
8
|
|
|
use Laminas\Diactoros\Response\InjectContentTypeTrait; |
|
9
|
|
|
use Laminas\Diactoros\Stream; |
|
10
|
|
|
use Psr\Http\Message\StreamInterface; |
|
11
|
|
|
|
|
12
|
|
|
class HtmlResponse extends Response |
|
13
|
|
|
{ |
|
14
|
|
|
use InjectContentTypeTrait; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* Create an HTML response. |
|
18
|
|
|
* |
|
19
|
|
|
* Produces an HTML response with a Content-Type of text/html and a default |
|
20
|
|
|
* status of 200. |
|
21
|
|
|
* |
|
22
|
|
|
* @param string|StreamInterface $html HTML or stream for the message body. |
|
23
|
|
|
* @param int $status Integer status code for the response; 200 by default. |
|
24
|
|
|
* @param array $headers Array of headers to use at initialization. |
|
25
|
|
|
* @throws Exception\InvalidArgumentException if $html is neither a string or stream. |
|
26
|
|
|
*/ |
|
27
|
3 |
|
public function __construct($html, int $status = 200, array $headers = []) |
|
28
|
|
|
{ |
|
29
|
3 |
|
parent::__construct( |
|
30
|
3 |
|
$this->createBody($html), |
|
31
|
|
|
$status, |
|
32
|
3 |
|
$this->injectContentType('text/html; charset=utf-8', $headers) |
|
33
|
|
|
); |
|
34
|
3 |
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* Create the message body. |
|
38
|
|
|
* |
|
39
|
|
|
* @param string|StreamInterface $html |
|
40
|
|
|
* @throws Exception\InvalidArgumentException if $html is neither a string or stream. |
|
41
|
|
|
*/ |
|
42
|
3 |
|
private function createBody($html) : StreamInterface |
|
43
|
|
|
{ |
|
44
|
3 |
|
if ($html instanceof StreamInterface) { |
|
45
|
1 |
|
return $html; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
3 |
|
if (! is_string($html)) { |
|
|
|
|
|
|
49
|
1 |
|
throw new InvalidArgumentException(sprintf( |
|
50
|
1 |
|
'Invalid content (%s) provided to %s', |
|
51
|
1 |
|
(is_object($html) ? get_class($html) : gettype($html)), |
|
52
|
1 |
|
__CLASS__ |
|
53
|
|
|
)); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
2 |
|
$body = new Stream('php://temp', 'wb+'); |
|
57
|
2 |
|
$body->write($html); |
|
58
|
2 |
|
$body->rewind(); |
|
59
|
|
|
|
|
60
|
2 |
|
return $body; |
|
61
|
|
|
} |
|
62
|
|
|
} |