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