DefaultParser   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 96.77%

Importance

Changes 0
Metric Value
wmc 12
lcom 0
cbo 2
dl 0
loc 72
ccs 30
cts 31
cp 0.9677
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A parse() 0 15 4
B parseImpl() 0 18 5
A parseSentence() 0 21 3
1
<?php
2
namespace Nkey\Caribu\Console;
3
4
/**
5
 * This class is part of Caribu command line interface framework
6
 *
7
 * @author Maik Greubel <[email protected]>
8
 */
9
class DefaultParser implements Parser
10
{
11
12
    /**
13
     * (non-PHPdoc)
14
     *
15
     * @see \Nkey\Caribu\Console\Parser::parse()
16
     */
17 5
    public function parse(string $input): ParsedCommand
18
    {
19 5
        list ($cmd, $params) = $this->parseImpl($input);
20 4
        $args = $this->parseSentence($params);
21
        
22 4
        $tmp = array();
23 4
        foreach ($args as $arg) {
24 4
            if (is_string($arg) && ! empty($arg)) {
25 4
                $tmp[] = $arg;
26
            }
27
        }
28 4
        $args = $tmp;
29
        
30 4
        return new ParsedCommand($cmd, $args);
31
    }
32
33
    /**
34
     * Internal parsing of input
35
     *
36
     * @param string $input
37
     * @throws ParserException
38
     * @return array
39
     */
40 5
    private function parseImpl(string $input): array
41
    {
42 5
        $pattern = '#(?<cmd>^"[^"]*"|\S*) *(?<prm>.*)?#';
43
        
44 5
        $matches = array();
45 5
        if (! preg_match($pattern, $input, $matches)) {
46
            throw new ParserException("Could not parse command");
47
        }
48 5
        $cmd = $matches['cmd'];
49 5
        if (empty($cmd) || strchr($cmd, '"') || strchr($cmd, "'")) {
50 1
            throw new ParserException("Could not parse command");
51
        }
52
        
53
        return array(
54 4
            $cmd,
55 4
            $matches['prm']
56
        );
57
    }
58
59 4
    private function parseSentence(string $param): array
60
    {
61 4
        $sentencePattern = '#[^\s"\']+|"([^"]*)"|\'([^\']*)\'#';
62
        
63 4
        $args = array();
64
        
65 4
        if (! preg_match_all($sentencePattern, $param, $args)) {
66 2
            $args[] = $param;
67
        } else {
68 2
            $realArgs = array();
69 2
            foreach ($args[0] as $arg) {
70 2
                $realArgs[] = str_replace(array(
71 2
                    '"',
72
                    "'"
73 2
                ), '', $arg);
74
            }
75 2
            $args = $realArgs;
76
        }
77
        
78 4
        return $args;
79
    }
80
}
81