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 * @copyright Copyright (c) 2025-2026 Felipe SayĆ£o Lobato Abreu <github@mentordosnerds.com>
12 * @license   https://opensource.org/licenses/MIT MIT License
13 *
14 * @see       https://github.com/php-fast-forward/http-message
15 * @see       https://github.com/php-fast-forward
16 * @see       https://datatracker.ietf.org/doc/html/rfc2119
17 */
18
19namespace FastForward\Http\Message;
20
21use FastForward\Http\Message\Header\ContentType;
22use Nyholm\Psr7\Response;
23use Nyholm\Psr7\Stream;
24
25/**
26 * Class HtmlResponse.
27 *
28 * Represents an HTTP response containing HTML content.
29 *
30 * This class MUST be used to generate HTTP responses with a `text/html` content type.
31 * It automatically sets the 'Content-Type' header, encodes the body using the specified charset,
32 * and applies the HTTP 200 (OK) status code by default.
33 */
34final class HtmlResponse extends Response
35{
36    /**
37     * Constructs a new HtmlResponse instance.
38     *
39     * This constructor SHALL set the 'Content-Type' header to `text/html` with the specified charset
40     * and initialize the response body with the provided HTML content. The response status code
41     * will be set to 200 (OK) by default, with the corresponding reason phrase.
42     *
43     * @param string $html the HTML content to send in the response body
44     * @param string $charset The character encoding to declare in the 'Content-Type' header. Defaults to 'utf-8'.
45     * @param array $headers optional additional headers to include in the response
46     */
47    public function __construct(string $html, string $charset = 'utf-8', array $headers = [])
48    {
49        $headers['Content-Type'] = ContentType::TextHtml->withCharset($charset);
50
51        parent::__construct(
52            status: StatusCode::Ok->value,
53            headers: $headers,
54            body: Stream::create($html),
55            reason: StatusCode::Ok->getReasonPhrase(),
56        );
57    }
58}