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

DirectiveHeader::getDirectives()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 6
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 11
ccs 0
cts 7
cp 0
crap 20
rs 10
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