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