1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10: 11:
12:
13:
14:
15: 16: 17: 18: 19: 20:
21: class NSimpleRouter extends NObject implements IRouter
22: {
23: const PRESENTER_KEY = 'presenter';
24: const MODULE_KEY = 'module';
25:
26:
27: private $module = '';
28:
29:
30: private $defaults;
31:
32:
33: private $flags;
34:
35:
36:
37: 38: 39: 40:
41: public function __construct($defaults = array(), $flags = 0)
42: {
43: if (is_string($defaults)) {
44: $a = strrpos($defaults, ':');
45: if (!$a) {
46: throw new InvalidArgumentException("Argument must be array or string in format Presenter:action, '$defaults' given.");
47: }
48: $defaults = array(
49: self::PRESENTER_KEY => substr($defaults, 0, $a),
50: 'action' => $a === strlen($defaults) - 1 ? 'default' : substr($defaults, $a + 1),
51: );
52: }
53:
54: if (isset($defaults[self::MODULE_KEY])) {
55: $this->module = $defaults[self::MODULE_KEY] . ':';
56: unset($defaults[self::MODULE_KEY]);
57: }
58:
59: $this->defaults = $defaults;
60: $this->flags = $flags;
61: }
62:
63:
64:
65: 66: 67: 68: 69:
70: public function match(IHttpRequest $httpRequest)
71: {
72:
73: $params = $httpRequest->getQuery();
74: $params += $this->defaults;
75:
76: if (!isset($params[self::PRESENTER_KEY])) {
77: throw new InvalidStateException('Missing presenter.');
78: }
79:
80: $presenter = $this->module . $params[self::PRESENTER_KEY];
81: unset($params[self::PRESENTER_KEY]);
82:
83: return new NPresenterRequest(
84: $presenter,
85: $httpRequest->getMethod(),
86: $params,
87: $httpRequest->getPost(),
88: $httpRequest->getFiles(),
89: array(NPresenterRequest::SECURED => $httpRequest->isSecured())
90: );
91: }
92:
93:
94:
95: 96: 97: 98: 99: 100:
101: public function constructUrl(NPresenterRequest $appRequest, IHttpRequest $httpRequest)
102: {
103: $params = $appRequest->getParams();
104:
105:
106: $presenter = $appRequest->getPresenterName();
107: if (strncasecmp($presenter, $this->module, strlen($this->module)) === 0) {
108: $params[self::PRESENTER_KEY] = substr($presenter, strlen($this->module));
109: } else {
110: return NULL;
111: }
112:
113:
114: foreach ($this->defaults as $key => $value) {
115: if (isset($params[$key]) && $params[$key] == $value) {
116: unset($params[$key]);
117: }
118: }
119:
120: $uri = $httpRequest->getUri();
121: $uri = ($this->flags & self::SECURED ? 'https://' : 'http://') . $uri->getAuthority() . $uri->getScriptPath();
122: $sep = ini_get('arg_separator.input');
123: $query = http_build_query($params, '', $sep ? $sep[0] : '&');
124: if ($query != '') {
125: $uri .= '?' . $query;
126: }
127: return $uri;
128: }
129:
130:
131:
132: 133: 134: 135:
136: public function getDefaults()
137: {
138: return $this->defaults;
139: }
140:
141: }
142: