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