sfPatternRouting.class.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. <?php
  2. /*
  3. * This file is part of the symfony package.
  4. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  5. *
  6. * For the full copyright and license information, please view the LICENSE
  7. * file that was distributed with this source code.
  8. */
  9. /**
  10. * sfPatternRouting class controls the generation and parsing of URLs.
  11. *
  12. * It parses and generates URLs by delegating the work to an array of sfRoute objects.
  13. *
  14. * @package symfony
  15. * @subpackage routing
  16. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  17. * @version SVN: $Id: sfPatternRouting.class.php 13288 2008-11-23 21:35:40Z fabien $
  18. */
  19. class sfPatternRouting extends sfRouting
  20. {
  21. protected
  22. $currentRouteName = null,
  23. $currentInternalUri = array(),
  24. $routes = array(),
  25. $cacheData = array(),
  26. $cacheChanged = false;
  27. /**
  28. * Initializes this Routing.
  29. *
  30. * Available options:
  31. *
  32. * * suffix: The default suffix
  33. * * variable_prefixes: An array of characters that starts a variable name (: by default)
  34. * * segment_separators: An array of allowed characters for segment separators (/ and . by default)
  35. * * variable_regex: A regex that match a valid variable name ([\w\d_]+ by default)
  36. * * generate_shortest_url: Whether to generate the shortest URL possible (true by default)
  37. * * extra_parameters_as_query_string: Whether to generate extra parameters as a query string
  38. *
  39. * @see sfRouting
  40. */
  41. public function initialize(sfEventDispatcher $dispatcher, sfCache $cache = null, $options = array())
  42. {
  43. $options = array_merge(array(
  44. 'variable_prefixes' => array(':'),
  45. 'segment_separators' => array('/', '.'),
  46. 'variable_regex' => '[\w\d_]+',
  47. 'load_configuration' => false,
  48. 'suffix' => '',
  49. 'generate_shortest_url' => true,
  50. 'extra_parameters_as_query_string' => true,
  51. ), $options);
  52. // for BC
  53. if ('.' == $options['suffix'])
  54. {
  55. $options['suffix'] = '';
  56. }
  57. parent::initialize($dispatcher, $cache, $options);
  58. if (!is_null($this->cache) && $cacheData = $this->cache->get('symfony.routing.data'))
  59. {
  60. $this->cacheData = unserialize($cacheData);
  61. }
  62. }
  63. /**
  64. * @see sfRouting
  65. */
  66. public function loadConfiguration()
  67. {
  68. if (!is_null($this->cache) && $routes = $this->cache->get('symfony.routing.configuration'))
  69. {
  70. $this->routes = unserialize($routes);
  71. }
  72. else
  73. {
  74. if ($this->options['load_configuration'] && $config = sfContext::getInstance()->getConfigCache()->checkConfig('config/routing.yml', true))
  75. {
  76. $this->setRoutes(include($config));
  77. }
  78. parent::loadConfiguration();
  79. if (!is_null($this->cache))
  80. {
  81. $this->cache->set('symfony.routing.configuration', serialize($this->routes));
  82. }
  83. }
  84. }
  85. /**
  86. * @see sfRouting
  87. */
  88. public function getCurrentInternalUri($withRouteName = false)
  89. {
  90. return is_null($this->currentRouteName) ? null : $this->currentInternalUri[$withRouteName ? 0 : 1];
  91. }
  92. /**
  93. * Gets the current route name.
  94. *
  95. * @return string The route name
  96. */
  97. public function getCurrentRouteName()
  98. {
  99. return $this->currentRouteName;
  100. }
  101. /**
  102. * @see sfRouting
  103. */
  104. public function getRoutes()
  105. {
  106. return $this->routes;
  107. }
  108. /**
  109. * @see sfRouting
  110. */
  111. public function setRoutes($routes)
  112. {
  113. foreach ($routes as $name => $route)
  114. {
  115. $this->connect($name, $route);
  116. }
  117. return $this->routes;
  118. }
  119. /**
  120. * @see sfRouting
  121. */
  122. public function hasRoutes()
  123. {
  124. return count($this->routes) ? true : false;
  125. }
  126. /**
  127. * @see sfRouting
  128. */
  129. public function clearRoutes()
  130. {
  131. if ($this->options['logging'])
  132. {
  133. $this->dispatcher->notify(new sfEvent($this, 'application.log', array('Clear all current routes')));
  134. }
  135. $this->routes = array();
  136. }
  137. /**
  138. * Returns true if the route name given is defined.
  139. *
  140. * @param string $name The route name
  141. *
  142. * @return boolean
  143. */
  144. public function hasRouteName($name)
  145. {
  146. return isset($this->routes[$name]) ? true : false;
  147. }
  148. /**
  149. * Adds a new route at the beginning of the current list of routes.
  150. *
  151. * @see connect
  152. */
  153. public function prependRoute($name, $route)
  154. {
  155. $routes = $this->routes;
  156. $this->routes = array();
  157. $newroutes = $this->connect($name, $route);
  158. $this->routes = array_merge($newroutes, $routes);
  159. return $this->routes;
  160. }
  161. /**
  162. * Adds a new route.
  163. *
  164. * Alias for the connect method.
  165. *
  166. * @see connect
  167. */
  168. public function appendRoute($name, $route)
  169. {
  170. return $this->connect($name, $route);
  171. }
  172. /**
  173. * Adds a new route before a given one in the current list of routes.
  174. *
  175. * @see connect
  176. */
  177. public function insertRouteBefore($pivot, $name, $route)
  178. {
  179. if (!isset($this->routes[$pivot]))
  180. {
  181. throw new sfConfigurationException(sprintf('Unable to insert route "%s" before inexistent route "%s".', $name, $pivot));
  182. }
  183. $routes = $this->routes;
  184. $this->routes = array();
  185. $newroutes = array();
  186. foreach ($routes as $key => $value)
  187. {
  188. if ($key == $pivot)
  189. {
  190. $newroutes = array_merge($newroutes, $this->connect($name, $route));
  191. }
  192. $newroutes[$key] = $value;
  193. }
  194. return $this->routes = $newroutes;
  195. }
  196. /**
  197. * Adds a new route at the end of the current list of routes.
  198. *
  199. * A route string is a string with 2 special constructions:
  200. * - :string: :string denotes a named paramater (available later as $request->getParameter('string'))
  201. * - *: * match an indefinite number of parameters in a route
  202. *
  203. * Here is a very common rule in a symfony project:
  204. *
  205. * <code>
  206. * $r->connect('default', new sfRoute('/:module/:action/*'));
  207. * </code>
  208. *
  209. * @param string $name The route name
  210. * @param sfRoute $route A sfRoute instance
  211. *
  212. * @return array current routes
  213. */
  214. public function connect($name, $route)
  215. {
  216. $routes = $route instanceof sfRouteCollection ? $route : array($name => $route);
  217. foreach (self::flattenRoutes($routes) as $name => $route)
  218. {
  219. $this->routes[$name] = $route;
  220. $this->configureRoute($route);
  221. if ($this->options['logging'])
  222. {
  223. $this->dispatcher->notify(new sfEvent($this, 'application.log', array(sprintf('Connect %s "%s" (%s)', get_class($route), $name, $route->getPattern()))));
  224. }
  225. }
  226. return $this->routes;
  227. }
  228. public function configureRoute(sfRoute $route)
  229. {
  230. $route->setDefaultParameters($this->defaultParameters);
  231. $route->setDefaultOptions($this->options);
  232. }
  233. /**
  234. * Sets a default parameter.
  235. *
  236. * @param string $key The key
  237. * @param string $value The value
  238. */
  239. public function setDefaultParameter($key, $value)
  240. {
  241. parent::setDefaultParameter($key, $value);
  242. foreach ($this->routes as $route)
  243. {
  244. $route->setDefaultParameters($this->defaultParameters);
  245. }
  246. }
  247. /**
  248. * Sets the default parameters for URL generation.
  249. *
  250. * @param array $parameters An array of default parameters
  251. */
  252. public function setDefaultParameters($parameters)
  253. {
  254. parent::setDefaultParameters($parameters);
  255. foreach ($this->routes as $route)
  256. {
  257. $route->setDefaultParameters($this->defaultParameters);
  258. }
  259. }
  260. /**
  261. * @see sfRouting
  262. */
  263. public function generate($name, $params = array(), $absolute = false)
  264. {
  265. // fetch from cache
  266. if (!is_null($this->cache))
  267. {
  268. $cacheKey = 'generate_'.$name.'_'.md5(serialize(array_merge($this->defaultParameters, $params))).'_'.md5(serialize($this->options['context']));
  269. if (isset($this->cacheData[$cacheKey]))
  270. {
  271. return $this->fixGeneratedUrl($this->cacheData[$cacheKey], $absolute);
  272. }
  273. }
  274. if ($name)
  275. {
  276. // named route
  277. if (!isset($this->routes[$name]))
  278. {
  279. throw new sfConfigurationException(sprintf('The route "%s" does not exist.', $name));
  280. }
  281. $route = $this->routes[$name];
  282. }
  283. else
  284. {
  285. // find a matching route
  286. if (false === $route = $this->getRouteThatMatchesParameters($params, $this->options['context']))
  287. {
  288. throw new sfConfigurationException(sprintf('Unable to find a matching route to generate url for params "%s".', is_object($params) ? 'Object('.get_class($params).')' : str_replace("\n", '', var_export($params, true))));
  289. }
  290. }
  291. $url = $route->generate($params, $this->options['context'], $absolute);
  292. // store in cache
  293. if (!is_null($this->cache))
  294. {
  295. $this->cacheChanged = true;
  296. $this->cacheData[$cacheKey] = $url;
  297. }
  298. return $this->fixGeneratedUrl($url, $absolute);
  299. }
  300. /**
  301. * @see sfRouting
  302. */
  303. public function parse($url)
  304. {
  305. if (false === $info = $this->findRoute($url))
  306. {
  307. return false;
  308. }
  309. if ($this->options['logging'])
  310. {
  311. $this->dispatcher->notify(new sfEvent($this, 'application.log', array(sprintf('Match route "%s" (%s) for %s with parameters %s', $info['name'], $info['pattern'], $url, str_replace("\n", '', var_export($info['parameters'], true))))));
  312. }
  313. // store the current internal URI
  314. $this->updateCurrentInternalUri($info['name'], $info['parameters']);
  315. $route = $this->routes[$info['name']];
  316. $route->bind($this->options['context'], $info['parameters']);
  317. $info['parameters']['_sf_route'] = $route;
  318. return $info['parameters'];
  319. }
  320. protected function updateCurrentInternalUri($name, array $parameters)
  321. {
  322. // store the route name
  323. $this->currentRouteName = $name;
  324. $internalUri = array('@'.$this->currentRouteName, $parameters['module'].'/'.$parameters['action']);
  325. unset($parameters['module'], $parameters['action']);
  326. $params = array();
  327. foreach ($parameters as $key => $value)
  328. {
  329. $params[] = $key.'='.$value;
  330. }
  331. // sort to guaranty unicity
  332. sort($params);
  333. $params = $params ? '?'.implode('&', $params) : '';
  334. $this->currentInternalUri = array($internalUri[0].$params, $internalUri[1].$params);
  335. }
  336. /**
  337. * Finds a matching route for given URL.
  338. *
  339. * Returns false if no route matches.
  340. *
  341. * Returned array contains:
  342. *
  343. * - name: name or alias of the route that matched
  344. * - route: the actual matching route object
  345. * - parameters: array containing key value pairs of the request parameters including defaults
  346. *
  347. * @param string $url URL to be parsed
  348. *
  349. * @return array|false An array with routing information or false if no route matched
  350. */
  351. public function findRoute($url)
  352. {
  353. $url = $this->normalizeUrl($url);
  354. // fetch from cache
  355. if (!is_null($this->cache))
  356. {
  357. $cacheKey = 'parse_'.$url.'_'.md5(serialize($this->options['context']));
  358. if (isset($this->cacheData[$cacheKey]))
  359. {
  360. return $this->cacheData[$cacheKey];
  361. }
  362. }
  363. $info = $this->getRouteThatMatchesUrl($url);
  364. // store in cache
  365. if (!is_null($this->cache))
  366. {
  367. $this->cacheChanged = true;
  368. $this->cacheData[$cacheKey] = $info;
  369. }
  370. return $info;
  371. }
  372. static public function flattenRoutes($routes)
  373. {
  374. $flattenRoutes = array();
  375. foreach ($routes as $name => $route)
  376. {
  377. if ($route instanceof sfRouteCollection)
  378. {
  379. $flattenRoutes = array_merge($flattenRoutes, self::flattenRoutes($route));
  380. }
  381. else
  382. {
  383. $flattenRoutes[$name] = $route;
  384. }
  385. }
  386. return $flattenRoutes;
  387. }
  388. protected function getRouteThatMatchesUrl($url)
  389. {
  390. foreach ($this->routes as $name => $route)
  391. {
  392. if (false === $parameters = $route->matchesUrl($url, $this->options['context']))
  393. {
  394. continue;
  395. }
  396. return array('name' => $name, 'pattern' => $route->getPattern(), 'parameters' => $parameters);
  397. }
  398. return false;
  399. }
  400. protected function getRouteThatMatchesParameters($parameters)
  401. {
  402. foreach ($this->routes as $name => $route)
  403. {
  404. if ($route->matchesParameters($parameters, $this->options['context']))
  405. {
  406. return $route;
  407. }
  408. }
  409. return false;
  410. }
  411. protected function normalizeUrl($url)
  412. {
  413. // an URL should start with a '/', mod_rewrite doesn't respect that, but no-mod_rewrite version does.
  414. if ('/' != $url[0])
  415. {
  416. $url = '/'.$url;
  417. }
  418. // we remove the query string
  419. if (false !== $pos = strpos($url, '?'))
  420. {
  421. $url = substr($url, 0, $pos);
  422. }
  423. // remove multiple /
  424. $url = preg_replace('#/+#', '/', $url);
  425. return $url;
  426. }
  427. /**
  428. * @see sfRouting
  429. */
  430. public function shutdown()
  431. {
  432. if (!is_null($this->cache) && $this->cacheChanged)
  433. {
  434. $this->cacheChanged = false;
  435. $this->cache->set('symfony.routing.data', serialize($this->cacheData));
  436. }
  437. }
  438. }