Completed
Pull Request — master (#87)
by Jan Philipp
01:57
created

ParameterParser::testParameterFormat()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php declare(strict_types=1);
2
3
namespace Shopware\Psh\Application;
4
5
class ParameterParser
6
{
7
    /**
8
     * @param array $params
9
     * @return array
10
     */
11
    public function parseParams(array $params): array
12
    {
13
        if (count($params) < 2) {
14
            return [];
15
        }
16
17
        $params = array_slice($params, 2);
18
19
        $reformattedParams = [];
20
        $paramsCount = count($params);
21
        for ($i = 0; $i < $paramsCount; $i++) {
22
            $key = $params[$i];
23
24
            $this->testParameterFormat($key);
25
26
            if ($this->isKeyValuePair($key)) {
27
                list($key, $value) = explode('=', $key, 2);
28
29
                if ($this->isEnclosedInAmpersand($value)) {
30
                    $value = substr($value, 1, -1);
31
                }
32
            } else {
33
                $i++;
34
                $value = $params[$i];
35
            }
36
37
            $key = str_replace('--', '', $key);
38
            $reformattedParams[strtoupper($key)] = $value;
39
        }
40
41
        return $reformattedParams;
42
    }
43
44
45
    /**
46
     * @param $key
47
     */
48
    private function testParameterFormat(string $key)
49
    {
50
        if (strpos($key, '--') !== 0) {
51
            throw new InvalidParameterException(
52
                sprintf('Unable to parse parameter %s. Use -- for correct usage', $key)
53
            );
54
        }
55
    }
56
57
    /**
58
     * @param $key
59
     * @return bool|int
60
     */
61
    private function isKeyValuePair($key)
62
    {
63
        return strpos($key, '=');
64
    }
65
66
    /**
67
     * @param $value
68
     * @return bool
69
     */
70
    private function isEnclosedInAmpersand($value): bool
71
    {
72
        return strpos($value, '"') === 0;
73
    }
74
}
75