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
<?php
/**
* @see https://github.com/laminas/laminas-diactoros for the canonical source repository
* @copyright https://github.com/laminas/laminas-diactoros/blob/master/COPYRIGHT.md
* @license https://github.com/laminas/laminas-diactoros/blob/master/LICENSE.md New BSD License
*/
declare(strict_types=1);
namespace Laminas\Diactoros\Response;
use Laminas\Diactoros\Exception;
use Laminas\Diactoros\Response;
use Laminas\Diactoros\Stream;
use Psr\Http\Message\StreamInterface;
use function get_class;
use function gettype;
use function is_object;
use function is_string;
use function sprintf;
/**
* HTML response.
*
* Allows creating a response by passing an HTML string to the constructor;
* by default, sets a status code of 200 and sets the Content-Type header to
* text/html.
*/
class HtmlResponse extends Response
{
use InjectContentTypeTrait;
/**
* Create an HTML response.
*
* Produces an HTML response with a Content-Type of text/html and a default
* status of 200.
*
* @param string|StreamInterface $html HTML or stream for the message body.
* @param int $status Integer status code for the response; 200 by default.
* @param array $headers Array of headers to use at initialization.
* @throws Exception\InvalidArgumentException if $html is neither a string or stream.
*/
public function __construct($html, int $status = 200, array $headers = [])
{
parent::__construct(
$this->createBody($html),
$status,
$this->injectContentType('text/html; charset=utf-8', $headers)
);
}
/**
* Create the message body.
*
* @param string|StreamInterface $html
* @throws Exception\InvalidArgumentException if $html is neither a string or stream.
*/
private function createBody($html) : StreamInterface
{
if ($html instanceof StreamInterface) {
return $html;
}
if (! is_string($html)) {
throw new Exception\InvalidArgumentException(sprintf(
'Invalid content (%s) provided to %s',
(is_object($html) ? get_class($html) : gettype($html)),
__CLASS__
));
}
$body = new Stream('php://temp', 'wb+');
$body->write($html);
$body->rewind();
return $body;
}
}