Completed
Pull Request — develop (#27)
by Chris
04:25
created

AbstractAttributeList::transform()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
c 0
b 0
f 0
rs 8.6737
cc 6
eloc 13
nc 8
nop 1
1
<?php
2
3
namespace Chrisyue\PhpM3u8\M3u8\Transformer;
4
5
abstract class AbstractAttributeList implements TransformerInterface
6
{
7
    public function transform($origin)
8
    {
9
        preg_match_all('/(?<=^|,)[A-Z0-9-]+=("?).+?\1(?=,|$)/', $origin, $matches);
10
11
        $result = $this->initResult();
12
        $parsed = false;
13
        foreach ($matches[0] as $attr) {
14
            list($name, $value) = explode('=', $attr);
15
            foreach ($this->getAttributeM3u8s() as $property => $m3u8) {
16
                if (null !== $result->$property || $m3u8->getName() !== $name) {
17
                    continue;
18
                }
19
20
                $result->$property = $m3u8->parse($value);
21
                $parsed = true;
22
23
                break;
24
            }
25
        }
26
27
        return $parsed ? $result : null;
28
    }
29
30
    public function reverse($result)
31
    {
32
        $keyVals = [];
33
        foreach ($this->getAttributeM3u8s() as $property => $m3u8) {
34
            if (null === $result->$property) {
35
                continue;
36
            }
37
38
            $keyVals[] = sprintf('%s=%s', $m3u8->getName(), $m3u8->dump($result->$property));
39
        }
40
41
        return implode(',', $keyVals);
42
    }
43
44
    abstract protected function getAttributeM3u8s();
45
46
    abstract protected function initResult();
47
}
48