ArgParser   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 25
dl 0
loc 63
rs 10
c 0
b 0
f 0
wmc 15

6 Methods

Rating   Name   Duplication   Size   Complexity  
A numericArg() 0 9 4
A letterArg() 0 12 4
A splitArg() 0 8 2
A __construct() 0 3 1
A getAdjustedArg() 0 6 2
A getArg() 0 8 2
1
<?php
2
namespace exussum12\CoverageChecker;
3
4
use exussum12\CoverageChecker\Exceptions\ArgumentNotFound;
5
6
class ArgParser
7
{
8
    protected $args;
9
10
    public function __construct(array $args)
11
    {
12
        $this->args = $args;
13
    }
14
15
    /**
16
     * @throws ArgumentNotFound
17
     */
18
    public function getArg(string $name): string
19
    {
20
        if (is_numeric($name)) {
21
            $name = (int) $name;
22
            return $this->numericArg($name);
23
        }
24
25
        return $this->letterArg($name);
26
    }
27
28
    protected function numericArg(int $position): string
29
    {
30
        foreach ($this->args as $arg) {
31
            if ($arg{0} != '-' && $position-- == 0) {
32
                return $arg;
33
            }
34
        }
35
36
        throw new ArgumentNotFound();
37
    }
38
39
    protected function letterArg($name): string
40
    {
41
        $name = $this->getAdjustedArg($name);
42
        foreach ($this->args as $arg) {
43
            list($value, $arg) = $this->splitArg($arg);
44
45
            if ($arg{0} == '-' && $name == $arg) {
46
                return $value;
47
            }
48
        }
49
50
        throw new ArgumentNotFound();
51
    }
52
53
    protected function splitArg(string $arg): array
54
    {
55
        $value = '1';
56
        if (strpos($arg, '=') > 0) {
57
            list($arg, $value) = explode('=', $arg, 2);
58
        }
59
60
        return array($value, $arg);
61
    }
62
63
    protected function getAdjustedArg(string $name): string
64
    {
65
        $name = strlen($name) == 1 ?
66
            '-' . $name :
67
            '--' . $name;
68
        return $name;
69
    }
70
}
71