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