1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* It's free open-source software released under the MIT License. |
5
|
|
|
* |
6
|
|
|
* @author Anatoly Nekhay <[email protected]> |
7
|
|
|
* @copyright Copyright (c) 2018, Anatoly Nekhay |
8
|
|
|
* @license https://github.com/sunrise-php/http-message/blob/master/LICENSE |
9
|
|
|
* @link https://github.com/sunrise-php/http-message |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Sunrise\Http\Message\Response; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Import classes |
16
|
|
|
*/ |
17
|
|
|
use Psr\Http\Message\StreamInterface; |
18
|
|
|
use Sunrise\Http\Message\Exception\InvalidArgumentException; |
19
|
|
|
use Sunrise\Http\Message\Response; |
20
|
|
|
use Sunrise\Http\Message\Stream\PhpTempStream; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Import functions |
24
|
|
|
*/ |
25
|
|
|
use function is_object; |
26
|
|
|
use function is_string; |
27
|
|
|
use function method_exists; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* HTML Response |
31
|
|
|
*/ |
32
|
|
|
class HtmlResponse extends Response |
33
|
|
|
{ |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* The response content type |
37
|
|
|
* |
38
|
|
|
* @var string |
39
|
|
|
*/ |
40
|
|
|
public const CONTENT_TYPE = 'text/html; charset=utf-8'; |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Constructor of the class |
44
|
|
|
* |
45
|
|
|
* @param int $statusCode |
46
|
|
|
* @param mixed $html |
47
|
|
|
* |
48
|
|
|
* @throws InvalidArgumentException |
49
|
|
|
*/ |
50
|
4 |
|
public function __construct(int $statusCode, $html) |
51
|
|
|
{ |
52
|
4 |
|
$body = $this->createBody($html); |
53
|
|
|
|
54
|
3 |
|
$headers = ['Content-Type' => self::CONTENT_TYPE]; |
55
|
|
|
|
56
|
3 |
|
parent::__construct($statusCode, null, $headers, $body); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* Creates the response body from the given HTML |
61
|
|
|
* |
62
|
|
|
* @param mixed $html |
63
|
|
|
* |
64
|
|
|
* @return StreamInterface |
65
|
|
|
* |
66
|
|
|
* @throws InvalidArgumentException |
67
|
|
|
* If the response body cannot be created from the given HTML. |
68
|
|
|
*/ |
69
|
4 |
|
private function createBody($html): StreamInterface |
70
|
|
|
{ |
71
|
4 |
|
if ($html instanceof StreamInterface) { |
72
|
1 |
|
return $html; |
73
|
|
|
} |
74
|
|
|
|
75
|
3 |
|
if (is_object($html) && method_exists($html, '__toString')) { |
76
|
|
|
/** @var string */ |
77
|
1 |
|
$html = $html->__toString(); |
78
|
|
|
} |
79
|
|
|
|
80
|
3 |
|
if (!is_string($html)) { |
81
|
1 |
|
throw new InvalidArgumentException('Unable to create HTML response due to invalid body'); |
82
|
|
|
} |
83
|
|
|
|
84
|
2 |
|
$stream = new PhpTempStream('r+b'); |
85
|
2 |
|
$stream->write($html); |
86
|
2 |
|
$stream->rewind(); |
87
|
|
|
|
88
|
2 |
|
return $stream; |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|