Passed
Push — master ( b02cff...0547e2 )
by Alexander
02:42
created

HtmlDataResponseFormatter::format()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 7
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Web\Data\Formatter;
6
7
use Psr\Http\Message\ResponseInterface;
8
use Yiisoft\Yii\Web\Data\DataResponse;
9
use Yiisoft\Yii\Web\Data\DataResponseFormatterInterface;
10
11
final class HtmlDataResponseFormatter implements DataResponseFormatterInterface
12
{
13
    /**
14
     * @var string the Content-Type header for the response
15
     */
16
    private string $contentType = 'text/html';
17
18
    /**
19
     * @var string the XML encoding.
20
     */
21
    private string $encoding = 'UTF-8';
22
23
    public function format(DataResponse $dataResponse): ResponseInterface
24
    {
25
        $data = $dataResponse->getData();
26
        $response = $dataResponse->getResponse();
27
        $response->getBody()->write((string)$data);
28
29
        return $response->withHeader('Content-Type', $this->contentType . '; charset=' . $this->encoding);
30
    }
31
32
    public function withEncoding(string $encoding): self
33
    {
34
        $formatter = clone $this;
35
        $formatter->encoding = $encoding;
36
        return $formatter;
37
    }
38
39
    public function withContentType(string $contentType): self
40
    {
41
        $formatter = clone $this;
42
        $this->contentType = $contentType;
43
        return $formatter;
44
    }
45
}
46