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

DirectiveHeader   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Test Coverage

Coverage 33.33%

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 40
ccs 6
cts 18
cp 0.3333
rs 10
c 0
b 0
f 0
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 2
A withDirective() 0 7 1
A getDirectives() 0 11 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Http\Header;
6
7
use InvalidArgumentException;
8
use Yiisoft\Http\Header\Internal\DirectivesHeaderValue;
9
use Yiisoft\Http\Header\Value\Unnamed\DirectiveValue;
10
11
final class DirectiveHeader extends Header
12
{
13
    protected const DEFAULT_VALUE_CLASS = DirectiveValue::class;
14
15 6
    public function __construct(string $nameOrClass)
16
    {
17 6
        parent::__construct($nameOrClass);
18 6
        if (!is_a($this->headerClass, DirectivesHeaderValue::class, true)) {
19 1
            throw new InvalidArgumentException(
20 1
                sprintf('%s class is not an instance of %s', $this->headerClass, DirectivesHeaderValue::class)
21
            );
22
        }
23 5
    }
24
25
    public function withDirective(string $directive, string $argument = null): self
26
    {
27
        $clone = clone $this;
28
        /** @var DirectivesHeaderValue $headerValue */
29
        $headerValue = new $this->headerClass();
30
        $clone->addValue($headerValue->withDirective($directive, $argument));
31
        return $clone;
32
    }
33
34
    /**
35
     * @param bool $ignoreIncorrect
36
     *
37
     * @return null[][]|string[][] Returns array of array<directive name => directive value>
38
     * @psalm-return array<int, array<string, null|string>>|array<empty, empty>
39
     */
40
    public function getDirectives(bool $ignoreIncorrect = true): array
41
    {
42
        $result = [];
43
        /** @var DirectivesHeaderValue $header */
44
        foreach ($this->collection as $header) {
45
            if ($ignoreIncorrect && $header->hasError()) {
46
                continue;
47
            }
48
            $result[] = [$header->getDirective() => $header->getArgument()];
49
        }
50
        return $result;
51
    }
52
}
53