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

DefaultParser   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 96.3%

Importance

Changes 0
Metric Value
wmc 11
lcom 0
cbo 2
dl 0
loc 56
ccs 26
cts 27
cp 0.963
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
C parse() 0 25 8
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
        $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