OptionMatcher::match()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
nc 3
nop 1
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 3
rs 10
c 1
b 0
f 0
1
<?php
2
3
/* this file is part of pipelines */
4
5
namespace Ktomk\Pipelines\Cli\Args;
6
7
/**
8
 * Class OptionMatcher
9
 *
10
 * Match one or multiple short/long opts
11
 *
12
 * @package Ktomk\Pipelines\Cli\Args
13
 */
14
class OptionMatcher
15
{
16
    /**
17
     * @var string[]
18
     */
19
    private $option;
20
21
    /**
22
     * @var bool
23
     */
24
    private $equals;
25
26
    /**
27
     * @param string $option
28
     * @param string $arg
29
     * @param bool $equals
30
     *
31
     * @return bool
32
     */
33 65
    public static function matchOptionArg($option, $arg, $equals)
34
    {
35 65
        $optLen = strlen($option);
36 65
        if (0 === $optLen) {
37 12
            return false;
38
        }
39
40 53
        $argLen = strlen($arg);
41 53
        if ($argLen < 2) {
42 4
            return false;
43
        }
44
45 49
        if ('--' === $arg) {
46 4
            return false;
47
        }
48
49 45
        if ('-' !== $arg[0]) {
50 4
            return false;
51
        }
52
53 41
        if ((1 !== $optLen) !== ('-' === $arg[1])) {
54 4
            return false;
55
        }
56
57 37
        $buffer = substr($arg, 1 === $optLen ? 1 : 2);
58
59 37
        if ($equals && false !== $posEquals = strpos($buffer, '=')) {
60 15
            if (0 === $posEquals) {
61 2
                return false;
62
            }
63 13
            $buffer = substr($buffer, 0, $posEquals);
64
        }
65
66 35
        if (1 === $optLen) {
67 22
            return false !== strpos($buffer, $option);
68
        }
69
70 13
        return $buffer === $option;
71
    }
72
73
    /**
74
     * @param string|string[] $option
75
     *
76
     * @return OptionMatcher
77
     */
78 1
    public static function create($option)
79
    {
80 1
        return new self($option, true);
81
    }
82
83
    /**
84
     * OptionMatcher constructor.
85
     *
86
     * @param string|string[] $option
87
     * @param bool $equals support equals-sign while matching
88
     */
89 33
    public function __construct($option, $equals)
90
    {
91 33
        $this->option = (array)$option;
92 33
        $this->equals = $equals;
93
    }
94
95
    /**
96
     * @param string $arg
97
     *
98
     * @return bool
99
     */
100 33
    public function match($arg)
101
    {
102 33
        foreach ($this->option as $option) {
103 33
            if (self::matchOptionArg($option, $arg, $this->equals)) {
104 11
                return true;
105
            }
106
        }
107
108 23
        return false;
109
    }
110
}
111