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

AbstractAttributeList::reverse()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
c 0
b 0
f 0
rs 9.4285
cc 3
eloc 8
nc 4
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->getTransformers() as $property => $transformer) {
16
                if (null !== $result->$property || $transformer->getName() !== $name) {
17
                    continue;
18
                }
19
20
                $result->$property = $transformer->transform($value);
21
                $parsed = true;
22
23
                break;
24
            }
25
        }
26
27
        return $parsed ? $result : null;
28
    }
29
30
    public function reverse($result)
31
    {
32
        $attributes = [];
33
        foreach ($this->getTransformers() as $property => $transformer) {
34
            $attributes[$transformer->getName()] = $result->$property;
35
        }
36
37
        $keyVals = [];
38
        foreach ($attributes as $name => $attribute) {
39
            $keyVals[] = sprintf('%s=%s', $name, $attribute);
40
        }
41
42
        return implode(',', $keyVals);
43
    }
44
45
    abstract protected function getTransformers();
46
47
    abstract protected function initResult();
48
}
49