HtmlResponse::createBody()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 10
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 19
ccs 11
cts 11
cp 1
crap 5
rs 9.6111
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
use Psr\Http\Message\StreamInterface;
15
use Sunrise\Http\Message\Exception\InvalidArgumentException;
16
use Sunrise\Http\Message\Response;
17
use Sunrise\Http\Message\Stream\PhpTempStream;
18
19
use function is_object;
20
use function is_string;
21
use function method_exists;
22
23
final class HtmlResponse extends Response
24
{
25
    /**
26
     * @param mixed $html
27
     *
28
     * @throws InvalidArgumentException
29
     */
30 4
    public function __construct(int $statusCode, $html)
31
    {
32 4
        parent::__construct($statusCode);
33
34 4
        $this->setBody(self::createBody($html));
35 3
        $this->setHeader('Content-Type', 'text/html; charset=utf-8');
36
    }
37
38
    /**
39
     * @param mixed $html
40
     *
41
     * @throws InvalidArgumentException
42
     */
43 4
    private static function createBody($html): StreamInterface
44
    {
45 4
        if ($html instanceof StreamInterface) {
46 1
            return $html;
47
        }
48
49 3
        if (is_object($html) && method_exists($html, '__toString')) {
50 1
            $html = (string) $html;
51
        }
52
53 3
        if (!is_string($html)) {
54 1
            throw new InvalidArgumentException('Unable to create the HTML response due to a unexpected HTML type');
55
        }
56
57 2
        $stream = new PhpTempStream('r+b');
58 2
        $stream->write($html);
59 2
        $stream->rewind();
60
61 2
        return $stream;
62
    }
63
}
64