Completed
Push — master ( 43e5a3...5bdf3f )
by Maik
06:46
created

DefaultParser::parse()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 5.005

Importance

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