Completed
Pull Request — master (#42)
by
unknown
14:56
created

SourceToArrayConverter::convert()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 0
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: execut
5
 * Date: 5/18/17
6
 * Time: 11:03 AM
7
 */
8
9
namespace pastuhov\ymlcatalog\categories;
10
11
12
use yii\base\Component;
13
14
class SourceToArrayConverter extends Component
15
{
16
    public $source = null;
17
    protected $result = [];
18
    public function convert() {
19
        $this->result = [];
20
        $this->parseList();
21
22
        return $this->result;
23
    }
24
25
    protected function parseList() {
26
        $source = str_replace("\n\n", "\n", str_replace("\r", "\n", $this->source));
27
        $rows = explode("\n", $source);
28
        foreach ($rows as $line => $row) {
29
            $fullName = trim($row);
30
            if (empty($fullName)) {
31
                continue;
32
            }
33
34
            $this->parseRow($fullName, $line);
35
        }
36
    }
37
38
    /**
39
     * @param $fullName
40
     * @param $line
41
     * @param $parentName
42
     * @return array
43
     */
44
    protected function parseRow($fullName, $line)
45
    {
46
        $id = md5($fullName);
47
        $result = [
48
            'id' => $id,
49
            'fullName' => $fullName,
50
            'line' => $line,
51
        ];
52
53
        $lastSlashPosition = mb_strrpos($fullName, '/');
54
        if ($lastSlashPosition) {
55
            do {
56
                $parentName = mb_substr($fullName, 0, $lastSlashPosition);
57
                $parentId = md5($parentName);
58
                $name = mb_substr($fullName, $lastSlashPosition + 1);
59
                $result = array_merge($result, [
60
                    'name' => $name,
61
                    'parent' => md5($parentName),
62
                ]);
63
                if (isset($this->result[$parentId])) {
64
                    break;
65
                } else {
66
                    $this->parseRow($parentName, $line);
67
                }
68
            } while(true);
69
        } else {
70
            $result['name'] = $fullName;
71
        }
72
73
        $this->result[$result['id']] = $result;
74
    }
75
}