ContentType::__construct()   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 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Stadly\Http\Header\Common;
6
7
use Stadly\Http\Exception\InvalidHeader;
8
use Stadly\Http\Header\Value\MediaType\MediaType;
9
use Stadly\Http\Utilities\Rfc7231;
10
11
/**
12
 * Class for handling the HTTP header field Content-Type.
13
 *
14
 * Specification: https://tools.ietf.org/html/rfc7231#section-3.1.1.5
15
 */
16
final class ContentType implements Header
17
{
18
    /**
19
     * @var MediaType Media type.
20
     */
21
    private $mediaType;
22
23
    /**
24
     * Constructor.
25
     *
26
     * @param MediaType $mediaType Media type.
27
     */
28 1
    public function __construct(MediaType $mediaType)
29
    {
30 1
        $this->setMediaType($mediaType);
31
    }
32
33
    /**
34
     * Construct header from value.
35
     *
36
     * @param string $value Header value.
37
     * @return self Header generated based on the value.
38
     * @throws InvalidHeader If the header value is invalid.
39
     */
40 2
    public static function fromValue(string $value): self
41
    {
42 2
        $regEx = '{^' . Rfc7231::CONTENT_TYPE . '$}';
43 2
        $plainValue = mb_convert_encoding($value, 'ISO-8859-1', 'UTF-8');
44 2
        if ($plainValue !== $value || preg_match($regEx, $value) !== 1) {
45 1
            throw new InvalidHeader('Invalid header value: ' . $value);
46
        }
47
48 1
        return new self(MediaType::fromString($value));
49
    }
50
51
    /**
52
     * @inheritDoc
53
     * @throws void The header is always valid.
54
     */
55 3
    public function __toString(): string
56
    {
57 3
        return $this->getName() . ': ' . $this->getValue();
58
    }
59
60
    /**
61
     * @return true The header is always valid.
62
     */
63 1
    public function isValid(): bool
64
    {
65 1
        return true;
66
    }
67
68
    /**
69
     * @inheritDoc
70
     */
71 1
    public function getName(): string
72
    {
73 1
        return 'Content-Type';
74
    }
75
76
    /**
77
     * @inheritDoc
78
     * @throws void The header is always valid.
79
     */
80 3
    public function getValue(): string
81
    {
82 3
        return (string)$this->mediaType;
83
    }
84
85
    /**
86
     * @return MediaType Media type.
87
     */
88 1
    public function getMediaType(): MediaType
89
    {
90 1
        return $this->mediaType;
91
    }
92
93
    /**
94
     * Set media type.
95
     *
96
     * @param MediaType $mediaType Media type.
97
     */
98 1
    public function setMediaType(MediaType $mediaType): void
99
    {
100 1
        $this->mediaType = $mediaType;
101
    }
102
}
103