normalizeArrayValue()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

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