Completed
Pull Request — develop (#27)
by Chris
10:40
created

AbstractParentCore::dump()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
c 0
b 0
f 0
rs 9.2
cc 4
eloc 9
nc 4
nop 1
1
<?php
2
3
namespace Chrisyue\PhpM3u8\M3u8\Core;
4
5
abstract class AbstractParentCore extends AbstractCore
6
{
7
    public function parse()
8
    {
9
        $parsedSequence = -1;
10
        $result = $this->initResult();
11
12
        do {
13
            $lineInfo = $this->getStream()->read();
14
            if (null === $lineInfo) {
15
                continue;
16
            }
17
18
            foreach ($this->getChildren() as $property => $parser) {
19
                if ($parser->getSequence() < $parsedSequence || null !== $result->$property && !is_array($result->$property)) {
20
                    continue;
21
                }
22
23
                $childResult = $parser->setStream($this->getStream())->parse();
24
                if (null === $childResult) {
25
                    continue;
26
                }
27
28
                is_array($result->$property) ? $result->$property[] = $childResult : $result->$property = $childResult;
29
                $parsedSequence = $parser->getSequence();
30
31
                break;
32
            }
33
        } while ($this->shouldParseNextLine($result, $parsedSequence) && $this->moveToNextLine());
34
35
        return $parsedSequence > -1 ? $result : null;
36
    }
37
38
    public function dump($result)
39
    {
40
        foreach ($this->getChildren() as $property => $dumper) {
41
            $childResult = $result->$property;
42
            if (null === $childResult) {
43
                continue;
44
            }
45
46
            $dumper->setStream($this->getStream());
47
48
            is_array($childResult) ? array_walk($childResult, function ($val) use ($dumper) {
49
                $dumper->dump($val);
50
            }) : $dumper->dump($childResult);
51
        }
52
    }
53
54
    abstract protected function initResult();
55
56
    abstract protected function shouldParseNextLine($result, $parsedSequence);
57
58
    abstract protected function getChildren();
59
60
    private function moveToNextLine()
61
    {
62
        $this->getStream()->next();
63
64
        return $this->getStream()->valid();
65
    }
66
}
67