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

DefaultParser   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 90.63%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
c 1
b 0
f 0
lcom 0
cbo 2
dl 0
loc 53
ccs 29
cts 32
cp 0.9063
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B parse() 0 22 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 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