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