Completed
Push — master ( 328faa...df6f67 )
by Maik
01:41
created

DefaultParser::parse()   C

Complexity

Conditions 8
Paths 5

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 8.0189

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 14
cts 15
cp 0.9333
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 15
nc 5
nop 1
crap 8.0189
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
        $pattern = '#(?<cmd>^"[^"]*"|\S*) *(?<prm>.*)?#';
20
        
21 5
        $matches = array();
22 5
        if (! preg_match($pattern, $input, $matches)) {
23
            throw new ParserException("Could not parse command");
24
        }
25 5
        $cmd = $matches['cmd'];
26 5
        if(empty($cmd) || strchr($cmd, '"') || strchr($cmd, "'")) {
27 1
        	throw new ParserException("Could not parse command");
28
        }
29
        
30 4
        $args = $this->parseSentence($matches['prm']);
31
        
32 4
        $tmp = array();
33 4
        foreach ($args as $arg) {
34 4
            if (is_string($arg) && ! empty($arg)) {
35 4
                $tmp[] = $arg;
36
            }
37
        }
38 4
        $args = $tmp;
39
        
40 4
        return new ParsedCommand($cmd, $args);
41
    }
42
43 4
    private function parseSentence(string $param): array
44
    {
45 4
        $sentencePattern = '#[^\s"\']+|"([^"]*)"|\'([^\']*)\'#';
46
        
47 4
        $args = array();
48
        
49 4
        if (! preg_match_all($sentencePattern, $param, $args)) {
50 2
            $args[] = $param;
51
        } else {
52 2
            $realArgs = array();
53 2
            foreach ($args[0] as $arg) {
54 2
                $realArgs[] = str_replace(array(
55 2
                    '"',
56
                    "'"
57 2
                ), '', $arg);
58
            }
59 2
            $args = $realArgs;
60
        }
61
        
62 4
        return $args;
63
    }
64
}
65