Passed
Push — master ( 4a0863...f9bf6d )
by Magnar Ovedal
03:47 queued 10s
created

Directive::fromString()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 11
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 20
ccs 12
cts 12
cp 1
crap 6
rs 9.2222
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Stadly\Http\Header\Value\CacheControl;
6
7
use InvalidArgumentException;
8
use Stadly\Http\Utilities\Rfc7234;
9
10
/**
11
 * Class for handling cache control directives.
12
 *
13
 * Specification: https://tools.ietf.org/html/rfc7234#section-5.2.2
14
 */
15
abstract class Directive
16
{
17
    /**
18
     * @var string Name.
19
     */
20
    protected $name;
21
22
    /**
23
     * Construct directive from string.
24
     *
25
     * @param string $directive Directive string.
26
     * @return self Directive generated based on the string.
27
     */
28 5
    public static function fromString(string $directive): self
29
    {
30 5
        $regEx = '{^' . Rfc7234::CACHE_DIRECTIVE_CAPTURE . '$}';
31 5
        if (utf8_decode($directive) !== $directive || preg_match($regEx, $directive, $matches) !== 1) {
32 1
            throw new InvalidArgumentException('Invalid directive: ' . $directive);
33
        }
34
35 4
        $name = strtolower($matches['NAME']);
36
37 4
        if (in_array($name, FieldListDirective::RESERVED_NAMES, /*strict*/true)) {
38 1
            return FieldListDirective::fromString($directive);
39
        }
40 3
        if (in_array($name, IntegerDirective::RESERVED_NAMES, /*strict*/true)) {
41 1
            return IntegerDirective::fromString($directive);
42
        }
43 2
        if (in_array($name, ValuelessDirective::RESERVED_NAMES, /*strict*/true)) {
44 1
            return ValuelessDirective::fromString($directive);
45
        }
46
47 1
        return GeneralDirective::fromString($directive);
48
    }
49
50
    /**
51
     * @return string String representation of the directive.
52
     */
53
    abstract public function __toString(): string;
54
55
    /**
56
     * @return string Name.
57
     */
58 4
    public function getName(): string
59
    {
60 4
        return $this->name;
61
    }
62
63
    /**
64
     * @param string $name Name.
65
     */
66
    abstract public function setName(string $name): void;
67
68
    /**
69
     * @return string|null Value.
70
     */
71
    abstract public function getValue(): ?string;
72
}
73