Passed
Pull Request — master (#26)
by Evgeniy
02:48
created

ErrorData   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 10
c 1
b 0
f 0
dl 0
loc 47
ccs 11
cts 11
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A __toString() 0 3 1
A addToResponse() 0 8 2
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 25
    public function __construct(string $content, array $headers = [])
29
    {
30 25
        $this->content = $content;
31 25
        $this->headers = $headers;
32 25
    }
33
34
    /**
35
     * Returns a content to use as response body.
36
     *
37
     * @return string The content to use as response body.
38
     */
39 11
    public function __toString(): string
40
    {
41 11
        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 10
    public function addToResponse(ResponseInterface $response): ResponseInterface
52
    {
53 10
        foreach ($this->headers as $name => $value) {
54 3
            $response = $response->withHeader($name, $value);
55
        }
56
57 10
        $response->getBody()->write($this->content);
58 10
        return $response;
59
    }
60
}
61