Passed
Pull Request — master (#22)
by Aleksei
02:39
created

ETag::withTag()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 7
ccs 6
cts 6
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Http\Header\Value\Condition;
6
7
use Yiisoft\Http\Header\Parser\ParsingException;
8
use Yiisoft\Http\Header\Internal\BaseHeaderValue;
9
10
/**
11
 * @link https://tools.ietf.org/html/rfc7232#section-2.3
12
 */
13
final class ETag extends BaseHeaderValue
14
{
15
    public const NAME = 'ETag';
16
17
    private string $tag = '';
18
    private bool $toStringFromTag = false;
19
    private bool $weak = true;
20
21 3
    public function __toString(): string
22
    {
23 3
        if ($this->toStringFromTag) {
24 1
            return ($this->weak ? 'W/' : '') . '"' . $this->tag . '"';
25
        }
26 2
        return $this->value;
27
    }
28
29 9
    public function getTag(): string
30
    {
31 9
        return $this->tag;
32
    }
33
34 9
    public function isWeak(): bool
35
    {
36 9
        return $this->weak;
37
    }
38
39 4
    public function withTag(string $tag, bool $weak = true): self
40
    {
41 4
        $clone = clone $this;
42 4
        $clone->tag = $tag;
43 4
        $clone->weak = $weak;
44 4
        $clone->toStringFromTag = true;
45 4
        return $clone;
46
    }
47
48 12
    protected function setValue(string $value): void
49
    {
50 12
        $this->value = trim($value);
51 12
        $this->toStringFromTag = false;
52 12
        if (preg_match('/^(?<weak>W\\/)?"(?<etagc>[^"\\x00-\\x20\\x7F]+)"$/', $this->value, $matches) === 1) {
53 5
            $this->tag = $matches['etagc'];
54 5
            $this->weak = $matches['weak'] === 'W/';
55 5
            $this->error = null;
56
        } else {
57 12
            $this->error = new ParsingException($value, 0, 'Invalid ETag value format', 0, $this->error);
58
        }
59 12
    }
60
}
61