Completed
Push — master ( 23bc19...2eec4d )
by Tomáš
11:42
created

CustomPropertyValuesExtractor::resolveArrayValue()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3.009

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 9
cts 10
cp 0.9
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 11
nc 3
nop 1
crap 3.009
1
<?php
2
3
/*
4
 * This file is part of Symplify
5
 * Copyright (c) 2016 Tomas Votruba (http://tomasvotruba.cz).
6
 */
7
8
namespace Symplify\PHP7_CodeSniffer\Ruleset\Extractor;
9
10
use SimpleXMLElement;
11
12
final class CustomPropertyValuesExtractor
13
{
14 5
    public function extractFromRulesetXmlFile(string $rulesetXmlFile) : array
15
    {
16 5
        $rulesetXml = simplexml_load_file($rulesetXmlFile);
17
18 5
        $customPropertyValues = [];
19 5
        foreach ($rulesetXml->rule as $ruleElement) {
20 5
            if (!isset($ruleElement['ref'])) {
21
                continue;
22
            }
23
24 5
            $customPropertyValues = array_merge(
25
                $customPropertyValues,
26 5
                $this->extractFromRuleXmlElement($ruleElement)
27
            );
28
        }
29
30 5
        return $customPropertyValues;
31
    }
32
33 8
    public function extractFromRuleXmlElement(SimpleXMLElement $ruleElement) : array
34
    {
35 8
        if (!isset($ruleElement->properties)) {
36 6
            return [];
37
        }
38
39 7
        $sniffCode = (string) $ruleElement['ref'];
40
41 7
        $customPropertyValues = [];
42 7
        foreach ($ruleElement->properties->property as $property) {
43 7
            $name = (string) $property['name'];
44 7
            $value = $this->resolveValue($property);
45 7
            $customPropertyValues[$sniffCode]['properties'][$name] = $value;
46
        }
47
48 7
        return $customPropertyValues;
49
    }
50
51
    /**
52
     * @return array|string
53
     */
54 7
    private function resolveValue(SimpleXMLElement $property)
55
    {
56 7
        if ($this->isArrayValue($property)) {
57 4
            return $this->resolveArrayValue($property);
58
        }
59
60 6
        return (string)$property['value'];
61
    }
62
63 7
    private function isArrayValue(SimpleXMLElement $property) : bool
64
    {
65 7
        return isset($property['type']) === true && (string)$property['type'] === 'array';
66
    }
67
68 4
    private function resolveArrayValue(SimpleXMLElement $arrayProperty) : array
69
    {
70 4
        $value = (string) $arrayProperty['value'];
71
72 4
        $values = [];
73 4
        foreach (explode(',', $value) as $val) {
74 4
            $v = '';
75
76 4
            list($key, $v) = explode('=>', $val . '=>');
77 4
            if ($v !== '') {
78
                $values[$key] = $v;
79
            } else {
80 4
                $values[] = $key;
81
            }
82
        }
83
84 4
        return $values;
85
    }
86
}
87