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
TextResponse
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 Nyholm\Psr7\Response;
22use Nyholm\Psr7\Stream;
23
24/**
25 * Class TextResponse.
26 *
27 * Represents an HTTP response containing plain text content.
28 *
29 * This class MUST be used to generate HTTP responses with a `text/plain` content type.
30 * It automatically sets the 'Content-Type' header, encodes the body using the specified charset,
31 * and applies the HTTP 200 (OK) status code by default.
32 */
33final class TextResponse extends Response
34{
35    /**
36     * Constructs a new TextResponse instance.
37     *
38     * This constructor SHALL set the 'Content-Type' header to `text/plain` with the specified charset
39     * and initialize the response body with the provided plain text content. The response status code
40     * will be set to 200 (OK) by default, with the corresponding reason phrase.
41     *
42     * @param string $text the plain text content to send in the response body
43     * @param string $charset The character encoding to declare in the 'Content-Type' header. Defaults to 'utf-8'.
44     * @param array $headers optional additional headers to include in the response
45     */
46    public function __construct(string $text, string $charset = 'utf-8', array $headers = [])
47    {
48        $headers['Content-Type'] = 'text/plain; charset=' . $charset;
49
50        parent::__construct(
51            status: StatusCode::Ok->value,
52            headers: $headers,
53            body: Stream::create($text),
54            reason: StatusCode::Ok->getReasonPhrase(),
55        );
56    }
57}