urlmapper.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. <?php
  2. /**
  3. * StatusNet - the distributed open-source microblogging tool
  4. * Copyright (C) 2011, StatusNet, Inc.
  5. *
  6. * URL mapper
  7. *
  8. * PHP version 5
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License as published by
  12. * the Free Software Foundation, either version 3 of the License, or
  13. * (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. *
  23. * @category URL
  24. * @package StatusNet
  25. * @author Evan Prodromou <evan@status.net>
  26. * @copyright 2011 StatusNet, Inc.
  27. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
  28. * @link http://status.net/
  29. */
  30. if (!defined('STATUSNET')) {
  31. // This check helps protect against security problems;
  32. // your code file can't be executed directly from the web.
  33. exit(1);
  34. }
  35. /**
  36. * URL mapper
  37. *
  38. * Converts a path into a set of parameters, and vice versa
  39. *
  40. * We used to use Net_URL_Mapper, so there's a wrapper class at Router, q.v.
  41. *
  42. * NUM's vagaries are the main reason we have weirdnesses here.
  43. *
  44. * @category URL
  45. * @package StatusNet
  46. * @author Evan Prodromou <evan@status.net>
  47. * @copyright 2011 StatusNet, Inc.
  48. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
  49. * @link http://status.net/
  50. */
  51. class URLMapper
  52. {
  53. const ACTION = 'action';
  54. protected $statics = array();
  55. protected $variables = array();
  56. protected $reverse = array();
  57. protected $allpaths = array();
  58. function connect($path, $args, $paramPatterns=array())
  59. {
  60. if (!array_key_exists(self::ACTION, $args)) {
  61. throw new Exception(sprintf("Can't connect %s; path has no action.", $path));
  62. }
  63. $this->allpaths[] = $path;
  64. $action = $args[self::ACTION];
  65. $paramNames = $this->getParamNames($path);
  66. if (empty($paramNames)) {
  67. $this->statics[$path] = $args;
  68. if (array_key_exists($action, $this->reverse)) {
  69. $this->reverse[$args[self::ACTION]][] = array($args, $path);
  70. } else {
  71. $this->reverse[$args[self::ACTION]] = array(array($args, $path));
  72. }
  73. } else {
  74. // Eff if I understand why some go here and some go there.
  75. // Anyways, fixup my preconceptions
  76. foreach ($paramNames as $name) {
  77. if (!array_key_exists($name, $paramPatterns) &&
  78. array_key_exists($name, $args)) {
  79. $paramPatterns[$name] = $args[$name];
  80. unset($args[$name]);
  81. }
  82. }
  83. $regex = self::makeRegex($path, $paramPatterns);
  84. $this->variables[] = array($args, $regex, $paramNames);
  85. $format = $this->makeFormat($path, $paramPatterns);
  86. if (array_key_exists($action, $this->reverse)) {
  87. $this->reverse[$args[self::ACTION]][] = array($args, $format, $paramNames);
  88. } else {
  89. $this->reverse[$args[self::ACTION]] = array(array($args, $format, $paramNames));
  90. }
  91. }
  92. }
  93. function match($path)
  94. {
  95. if (array_key_exists($path, $this->statics)) {
  96. return $this->statics[$path];
  97. }
  98. foreach ($this->variables as $pattern) {
  99. list($args, $regex, $paramNames) = $pattern;
  100. if (preg_match($regex, $path, $match)) {
  101. $results = $args;
  102. foreach ($paramNames as $name) {
  103. $results[$name] = $match[$name];
  104. }
  105. return $results;
  106. }
  107. }
  108. throw new NoRouteMapException($path);
  109. }
  110. function generate($args, $qstring, $fragment)
  111. {
  112. if (!array_key_exists(self::ACTION, $args)) {
  113. throw new Exception("Every path needs an action.");
  114. }
  115. $action = $args[self::ACTION];
  116. if (!array_key_exists($action, $this->reverse)) {
  117. throw new Exception(sprintf('No candidate paths for action "%s"', $action));
  118. }
  119. $candidates = $this->reverse[$action];
  120. foreach ($candidates as $candidate) {
  121. if (count($candidate) == 2) { // static
  122. list($tryArgs, $tryPath) = $candidate;
  123. foreach ($tryArgs as $key => $value) {
  124. if (!array_key_exists($key, $args) || $args[$key] != $value) {
  125. // next candidate
  126. continue 2;
  127. }
  128. }
  129. // success
  130. $path = $tryPath;
  131. } else {
  132. list($tryArgs, $format, $paramNames) = $candidate;
  133. foreach ($tryArgs as $key => $value) {
  134. if (!array_key_exists($key, $args) || $args[$key] != $value) {
  135. // next candidate
  136. continue 2;
  137. }
  138. }
  139. // success
  140. $toFormat = array();
  141. foreach ($paramNames as $name) {
  142. if (!array_key_exists($name, $args)) {
  143. // next candidate
  144. continue 2;
  145. }
  146. $toFormat[] = $args[$name];
  147. }
  148. $path = vsprintf($format, $toFormat);
  149. }
  150. if (!empty($qstring)) {
  151. $formatted = http_build_query($qstring);
  152. $path .= '?' . $formatted;
  153. }
  154. return $path;
  155. }
  156. // failure; some reporting twiddles
  157. unset($args['action']);
  158. if (empty($args)) {
  159. throw new Exception(sprintf('No matches for action "%s"', $action));
  160. }
  161. $argstring = '';
  162. foreach ($args as $key => $value) {
  163. $argstring .= "$key=$value ";
  164. }
  165. throw new Exception(sprintf('No matches for action "%s" with arguments "%s"', $action, $argstring));
  166. }
  167. protected function getParamNames($path)
  168. {
  169. preg_match_all('/:(?P<name>\w+)/', $path, $match);
  170. return $match['name'];
  171. }
  172. static function makeRegex($path, $paramPatterns)
  173. {
  174. $pr = new PatternReplacer($paramPatterns);
  175. $regex = preg_replace_callback('/:(\w+)/',
  176. array($pr, 'toPattern'),
  177. $path);
  178. $regex = '#^' . str_replace('#', '\#', $regex) . '$#';
  179. return $regex;
  180. }
  181. protected function makeFormat($path, $paramPatterns)
  182. {
  183. $format = preg_replace('/(:\w+)/', '%s', $path);
  184. return $format;
  185. }
  186. public function getPaths()
  187. {
  188. return $this->allpaths;
  189. }
  190. }
  191. class PatternReplacer
  192. {
  193. private $patterns;
  194. function __construct($patterns)
  195. {
  196. $this->patterns = $patterns;
  197. }
  198. function toPattern($matches)
  199. {
  200. // trim out the :
  201. $name = $matches[1];
  202. if (array_key_exists($name, $this->patterns)) {
  203. $pattern = $this->patterns[$name];
  204. } else {
  205. // ???
  206. $pattern = '\w+';
  207. }
  208. return '(?P<'.$name.'>'.$pattern.')';
  209. }
  210. }