Completed
Pull Request — develop (#27)
by Chris
05:29
created

Line::fromString()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.6
c 0
b 0
f 0
cc 4
nc 4
nop 1
1
<?php
2
3
namespace Chrisyue\PhpM3u8\Line;
4
5
class Line
6
{
7
    const TYPE_URI = 'uri';
8
    const TYPE_TAG = 'tag';
9
10
    private $tag;
11
12
    private $value;
13
14
    public function __construct($tag = null, $value = null)
15
    {
16
        if (null === $tag && null === $value) {
17
            throw new \InvalidArgumentException('$tag and $value can not both be null');
18
        }
19
20
        $this->tag = $tag;
21
        $this->value = $value;
22
    }
23
24
    static public function fromString($line)
25
    {
26
        $line = trim($line);
27
        if (empty($line)) {
28
            return;
29
        }
30
31
        if ('#' !== $line[0]) {
32
            return new Line(null, $line);
33
        }
34
35
        $line = ltrim($line, '#');
36
        if (empty($line)) {
37
            return;
38
        }
39
40
        list($tag, $value) = array_pad(explode(':', $line, 2), 2, true);
41
42
        return new self($tag, $value);
43
    }
44
45
    public function getTag()
46
    {
47
        return $this->tag;
48
    }
49
50
    public function getValue()
51
    {
52
        return $this->value;
53
    }
54
55
    public function isType($type)
56
    {
57
        return $this->getType() === $type;
58
    }
59
60
    public function __toString()
61
    {
62
        if ($this->isType(Line::TYPE_URI)) {
63
            return $this->value;
64
        }
65
66
        if (true === $this->value) {
67
            return sprintf('#%s', $this->tag);
68
        }
69
70
        if (false === $this->value) {
71
            return '';
72
        }
73
74
        return sprintf('#%s:%s', $this->tag, $this->value);
75
    }
76
77
    private function getType()
78
    {
79
        if (null !== $this->tag) {
80
            return self::TYPE_TAG;
81
        }
82
83
        return self::TYPE_URI;
84
    }
85
}
86