Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
CRAP
100.00% covered (success)
100.00%
1 / 1
HtmlResponse
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4
5/**
6 * This file is part of php-fast-forward/http-message.
7 *
8 * This source file is subject to the license bundled
9 * with this source code in the file LICENSE.
10 *
11 * @link      https://github.com/php-fast-forward/http-message
12 * @copyright Copyright (c) 2025 Felipe SayĆ£o Lobato Abreu <github@mentordosnerds.com>
13 * @license   https://opensource.org/licenses/MIT MIT License
14 */
15
16namespace FastForward\Http\Message;
17
18use Nyholm\Psr7\Response;
19use Nyholm\Psr7\Stream;
20
21/**
22 * Class HtmlResponse.
23 *
24 * Represents an HTTP response containing HTML content.
25 *
26 * This class MUST be used to generate HTTP responses with a `text/html` content type.
27 * It automatically sets the 'Content-Type' header, encodes the body using the specified charset,
28 * and applies the HTTP 200 (OK) status code by default.
29 *
30 * @package FastForward\Http\Message
31 */
32final class HtmlResponse extends Response
33{
34    /**
35     * Constructs a new HtmlResponse instance.
36     *
37     * This constructor SHALL set the 'Content-Type' header to `text/html` with the specified charset
38     * and initialize the response body with the provided HTML content. The response status code
39     * will be set to 200 (OK) by default, with the corresponding reason phrase.
40     *
41     * @param string                         $html    the HTML content to send in the response body
42     * @param string                         $charset The character encoding to declare in the 'Content-Type' header. Defaults to 'utf-8'.
43     * @param array<string, string|string[]> $headers optional additional headers to include in the response
44     */
45    public function __construct(string $html, string $charset = 'utf-8', array $headers = [])
46    {
47        $headers['Content-Type'] = 'text/html; charset=' . $charset;
48
49        parent::__construct(
50            status: StatusCode::Ok->value,
51            headers: $headers,
52            body: Stream::create($html),
53            reason: StatusCode::Ok->getReasonPhrase(),
54        );
55    }
56}