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
|
|
|
|