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

HtmlDataResponseFormatter   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 33
rs 10
wmc 3

3 Methods

Rating   Name   Duplication   Size   Complexity  
A withEncoding() 0 5 1
A withContentType() 0 5 1
A format() 0 7 1
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