Completed
Push — master ( 74ff7b...2fd8e1 )
by Tomáš
03:25
created

SniffPropertyValuesExtractor::resolveValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 2
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\Sniff\Xml\Extractor;
9
10
use SimpleXMLElement;
11
12
final class SniffPropertyValuesExtractor
13
{
14 9
    public function extractFromRuleXmlElement(SimpleXMLElement $ruleXmlElement) : array
15
    {
16 9
        if (!isset($ruleXmlElement->properties)) {
17 1
            return [];
18
        }
19
20 8
        $propertyValues = [];
21 8
        foreach ($ruleXmlElement->properties->property as $propertyXmlElement) {
22 8
            $name = (string) $propertyXmlElement['name'];
23 8
            $value = $this->normalizeValue((string) $propertyXmlElement['value'], $propertyXmlElement);
24 8
            $propertyValues[$name] = $value;
25
        }
26
27 8
        return $propertyValues;
28
    }
29
30
    /**
31
     * @return mixed
32
     */
33 8
    private function normalizeValue(string $value, SimpleXMLElement $propertyXmlElement)
34
    {
35 8
        $value = trim($value);
36
37 8
        if (is_numeric($value)) {
38 5
            return (int) $value;
39
        }
40
41 7
        if ($this->isArrayValue($propertyXmlElement)) {
42 5
            return $this->normalizeArrayValue($value);
43
        }
44
45 6
        return $this->normalizeBoolValue($value);
46
    }
47
48 7
    private function isArrayValue(SimpleXMLElement $property) : bool
49
    {
50 7
        return isset($property['type']) === true && (string) $property['type'] === 'array';
51
    }
52
53
    /**
54
     * @return mixed
55
     */
56 6
    private function normalizeBoolValue(string $value)
57
    {
58 6
        if ($value === 'true' || $value === 'TRUE') {
59 4
            return true;
60
        }
61
62 6
        if ($value === 'false' || $value === 'FALSE') {
63 1
            return false;
64
        }
65
66 6
        return $value;
67
    }
68
69 5
    private function normalizeArrayValue(string $value) : array
70
    {
71 5
        $values = [];
72 5
        foreach (explode(',', $value) as $val) {
73 5
            $v = '';
74
75 5
            list($key, $v) = explode('=>', $val . '=>');
76 5
            if ($v !== '') {
77 1
                $values[$key] = $v;
78
            } else {
79 5
                $values[] = $key;
80
            }
81
        }
82
83 5
        return $values;
84
    }
85
}
86