Passed
Pull Request — master (#26)
by Evgeniy
03:07
created

ErrorData::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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