Completed
Pull Request — develop (#27)
by Chris
12:16
created

AbstractStream::write()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
c 0
b 0
f 0
rs 9.4285
cc 3
eloc 8
nc 3
nop 1
1
<?php
2
3
namespace Chrisyue\PhpM3u8\Stream;
4
5
abstract class AbstractStream implements StreamInterface
6
{
7
    public function read()
8
    {
9
        static $line;
10
        static $lineInfo;
11
        if ($this->getLine() !== $line) {
12
            $line = $this->getLine();
13
            $lineInfo = $this->getLineInfo($line);
14
        }
15
16
        return $lineInfo;
17
    }
18
19
    public function write(array $lineInfo)
20
    {
21
        if (empty($lineInfo['tag'])) {
22
            $this->putLine($lineInfo['value']);
23
24
            return;
25
        }
26
27
        if (empty($lineInfo['value'])) {
28
            $this->putLine($lineInfo['tag']);
29
30
            return;
31
        }
32
33
        $this->putLine(sprintf('%s:%s', $lineInfo['tag'], $lineInfo['value']));
34
    }
35
36
    abstract protected function getLine();
37
38
    abstract protected function putLine($line);
39
40
    private function getLineInfo($line)
41
    {
42
        $line = trim($line);
43
        if (empty($line)) {
44
            return;
45
        }
46
47
        if ('#' !== $line[0]) {
48
            return ['value' => $line];
49
        }
50
51
        if (strlen($line) < 2) {
52
            return;
53
        }
54
55
        list($tag, $value) = array_pad(explode(':', $line, 2), 2, '');
56
57
        return compact('tag', 'value');
58
    }
59
}
60