1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ballen\Clip\Utilities; |
4
|
|
|
|
5
|
|
|
use Ballen\Collection\Collection; |
6
|
|
|
use Ballen\Clip\Exceptions\CommandNotFoundException; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Clip |
10
|
|
|
* |
11
|
|
|
* A package for speeding up development of PHP console (CLI) applications. |
12
|
|
|
* |
13
|
|
|
* @author Bobby Allen <[email protected]> |
14
|
|
|
* @license https://raw.githubusercontent.com/bobsta63/clip/master/LICENSE |
15
|
|
|
* @link https://github.com/allebb/clip |
16
|
|
|
* @link http://www.bobbyallen.me |
17
|
|
|
* |
18
|
|
|
*/ |
19
|
|
|
class CommandRouter |
20
|
|
|
{ |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Configured routes |
24
|
|
|
* @var Collection |
25
|
|
|
*/ |
26
|
|
|
private $routes; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* CLI arguments |
30
|
|
|
* @var ArgumentsParser |
31
|
|
|
*/ |
32
|
|
|
private $arguments; |
33
|
|
|
|
34
|
32 |
|
public function __construct($arguments = []) |
35
|
|
|
{ |
36
|
32 |
|
$this->routes = new Collection(); |
37
|
32 |
|
$this->arguments = new ArgumentsParser($arguments); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Register a new command handler. |
42
|
|
|
* @param string $command The command name |
43
|
|
|
* @param mixed $handler The command handler (see ClassMethodHandler) |
44
|
|
|
*/ |
45
|
24 |
|
public function add($command, $handler) |
46
|
|
|
{ |
47
|
24 |
|
$this->routes->put($command, $handler); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Dispatches the command handler. |
52
|
|
|
* @param string $call The command handler to execute. |
53
|
|
|
* @return void |
54
|
|
|
* @throws CommandNotFoundException |
55
|
|
|
*/ |
56
|
28 |
|
public function dispatch($call = null) |
57
|
|
|
{ |
58
|
28 |
|
$command = $this->routes->get($this->arguments->getCommand(1), false); |
|
|
|
|
59
|
28 |
|
if ($this->routes->get($call, false)) { |
60
|
24 |
|
$command = $this->routes->get($call, false); |
61
|
|
|
} |
62
|
28 |
|
if ($command) { |
63
|
24 |
|
$handler = new ClassMethodHandler($command, $this->arguments); |
|
|
|
|
64
|
8 |
|
return $handler->call($this->arguments); |
|
|
|
|
65
|
|
|
} |
66
|
4 |
|
throw new CommandNotFoundException(sprintf('Command %s is not registered.', $call)); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|