1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10:
11:
12: namespace Nette\Application;
13:
14: use Nette;
15:
16:
17:
18: 19: 20: 21: 22:
23: class CliRouter extends Nette\Object implements IRouter
24: {
25: const PRESENTER_KEY = 'action';
26:
27:
28: private $defaults;
29:
30:
31:
32: 33: 34:
35: public function __construct($defaults = array())
36: {
37: $this->defaults = $defaults;
38: }
39:
40:
41:
42: 43: 44: 45: 46:
47: public function match(Nette\Web\IHttpRequest $httpRequest)
48: {
49: if (empty($_SERVER['argv']) || !is_array($_SERVER['argv'])) {
50: return NULL;
51: }
52:
53: $names = array(self::PRESENTER_KEY);
54: $params = $this->defaults;
55: $args = $_SERVER['argv'];
56: array_shift($args);
57: $args[] = '--';
58:
59: foreach ($args as $arg) {
60: $opt = preg_replace('#/|-+#A', '', $arg);
61: if ($opt === $arg) {
62: if (isset($flag) || $flag = array_shift($names)) {
63: $params[$flag] = $arg;
64: } else {
65: $params[] = $arg;
66: }
67: $flag = NULL;
68: continue;
69: }
70:
71: if (isset($flag)) {
72: $params[$flag] = TRUE;
73: $flag = NULL;
74: }
75:
76: if ($opt !== '') {
77: $pair = explode('=', $opt, 2);
78: if (isset($pair[1])) {
79: $params[$pair[0]] = $pair[1];
80: } else {
81: $flag = $pair[0];
82: }
83: }
84: }
85:
86: if (!isset($params[self::PRESENTER_KEY])) {
87: throw new \InvalidStateException('Missing presenter & action in route definition.');
88: }
89: $presenter = $params[self::PRESENTER_KEY];
90: if ($a = strrpos($presenter, ':')) {
91: $params[self::PRESENTER_KEY] = substr($presenter, $a + 1);
92: $presenter = substr($presenter, 0, $a);
93: }
94:
95: return new PresenterRequest(
96: $presenter,
97: 'CLI',
98: $params
99: );
100: }
101:
102:
103:
104: 105: 106: 107: 108: 109:
110: public function constructUrl(PresenterRequest $appRequest, Nette\Web\IHttpRequest $httpRequest)
111: {
112: return NULL;
113: }
114:
115:
116:
117: 118: 119: 120:
121: public function getDefaults()
122: {
123: return $this->defaults;
124: }
125:
126: }
127: