ErrorData::__toString()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 1
c 1
b 1
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\ErrorHandler;
6
7
use Psr\Http\Message\ResponseInterface;
8
use Stringable;
9
10
/**
11
 * ErrorData stores content and headers that are suitable for adding to response.
12
 */
13
final class ErrorData implements Stringable
14
{
15
    /**
16
     * @param string $content The content to use as response body.
17
     * @param array<string, string|string[]> $headers The headers to add to the response.
18
     */
19 29
    public function __construct(
20
        private string $content,
21
        private array $headers = [],
22
    ) {
23 29
    }
24
25
    /**
26
     * Returns a content to use as response body.
27
     *
28
     * @return string The content to use as response body.
29
     */
30 13
    public function __toString(): string
31
    {
32 13
        return $this->content;
33
    }
34
35
    /**
36
     * Returns a response with error data.
37
     *
38
     * @param ResponseInterface $response The response for setting error data.
39
     *
40
     * @return ResponseInterface The response with error data.
41
     */
42 12
    public function addToResponse(ResponseInterface $response): ResponseInterface
43
    {
44 12
        foreach ($this->headers as $name => $value) {
45 3
            $response = $response->withHeader($name, $value);
46
        }
47
48 12
        $response
49 12
            ->getBody()
50 12
            ->write($this->content);
51 12
        return $response;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $response could return the type Psr\Http\Message\MessageInterface which includes types incompatible with the type-hinted return Psr\Http\Message\ResponseInterface. Consider adding an additional type-check to rule them out.
Loading history...
52
    }
53
}
54