Route.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @package Zend_Controller
  16. * @subpackage Router
  17. * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @version $Id$
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. */
  21. /** Zend_Controller_Router_Route_Abstract */
  22. require_once 'Zend/Controller/Router/Route/Abstract.php';
  23. /**
  24. * Route
  25. *
  26. * @package Zend_Controller
  27. * @subpackage Router
  28. * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
  29. * @license http://framework.zend.com/license/new-bsd New BSD License
  30. * @see http://manuals.rubyonrails.com/read/chapter/65
  31. */
  32. class Zend_Controller_Router_Route extends Zend_Controller_Router_Route_Abstract
  33. {
  34. /**
  35. * Default translator
  36. *
  37. * @var Zend_Translate
  38. */
  39. protected static $_defaultTranslator;
  40. /**
  41. * Translator
  42. *
  43. * @var Zend_Translate
  44. */
  45. protected $_translator;
  46. /**
  47. * Default locale
  48. *
  49. * @var mixed
  50. */
  51. protected static $_defaultLocale;
  52. /**
  53. * Locale
  54. *
  55. * @var mixed
  56. */
  57. protected $_locale;
  58. /**
  59. * Wether this is a translated route or not
  60. *
  61. * @var boolean
  62. */
  63. protected $_isTranslated = false;
  64. /**
  65. * Translatable variables
  66. *
  67. * @var array
  68. */
  69. protected $_translatable = array();
  70. protected $_urlVariable = ':';
  71. protected $_urlDelimiter = '/';
  72. protected $_regexDelimiter = '#';
  73. protected $_defaultRegex = null;
  74. /**
  75. * Holds names of all route's pattern variable names. Array index holds a position in URL.
  76. * @var array
  77. */
  78. protected $_variables = array();
  79. /**
  80. * Holds Route patterns for all URL parts. In case of a variable it stores it's regex
  81. * requirement or null. In case of a static part, it holds only it's direct value.
  82. * In case of a wildcard, it stores an asterisk (*)
  83. * @var array
  84. */
  85. protected $_parts = array();
  86. /**
  87. * Holds user submitted default values for route's variables. Name and value pairs.
  88. * @var array
  89. */
  90. protected $_defaults = array();
  91. /**
  92. * Holds user submitted regular expression patterns for route's variables' values.
  93. * Name and value pairs.
  94. * @var array
  95. */
  96. protected $_requirements = array();
  97. /**
  98. * Associative array filled on match() that holds matched path values
  99. * for given variable names.
  100. * @var array
  101. */
  102. protected $_values = array();
  103. /**
  104. * Associative array filled on match() that holds wildcard variable
  105. * names and values.
  106. * @var array
  107. */
  108. protected $_wildcardData = array();
  109. /**
  110. * Helper var that holds a count of route pattern's static parts
  111. * for validation
  112. * @var int
  113. */
  114. protected $_staticCount = 0;
  115. public function getVersion() {
  116. return 1;
  117. }
  118. /**
  119. * Instantiates route based on passed Zend_Config structure
  120. *
  121. * @param Zend_Config $config Configuration object
  122. */
  123. public static function getInstance(Zend_Config $config)
  124. {
  125. $reqs = ($config->reqs instanceof Zend_Config) ? $config->reqs->toArray() : array();
  126. $defs = ($config->defaults instanceof Zend_Config) ? $config->defaults->toArray() : array();
  127. return new self($config->route, $defs, $reqs);
  128. }
  129. /**
  130. * Prepares the route for mapping by splitting (exploding) it
  131. * to a corresponding atomic parts. These parts are assigned
  132. * a position which is later used for matching and preparing values.
  133. *
  134. * @param string $route Map used to match with later submitted URL path
  135. * @param array $defaults Defaults for map variables with keys as variable names
  136. * @param array $reqs Regular expression requirements for variables (keys as variable names)
  137. * @param array $reqs Regular expression requirements for variables (keys as variable names)
  138. * @param Zend_Translate $translator Translator to use for this instance
  139. */
  140. public function __construct($route, $defaults = array(), $reqs = array(), Zend_Translate $translator = null, $locale = null)
  141. {
  142. $route = trim($route, $this->_urlDelimiter);
  143. $this->_defaults = (array) $defaults;
  144. $this->_requirements = (array) $reqs;
  145. $this->_translator = $translator;
  146. $this->_locale = $locale;
  147. if ($route !== '') {
  148. foreach (explode($this->_urlDelimiter, $route) as $pos => $part) {
  149. if (substr($part, 0, 1) == $this->_urlVariable) {
  150. $name = substr($part, 1);
  151. if (substr($name, 0, 1) === '@') {
  152. $name = substr($name, 1);
  153. $this->_translatable[] = $name;
  154. $this->_isTranslated = true;
  155. }
  156. $this->_parts[$pos] = (isset($reqs[$name]) ? $reqs[$name] : $this->_defaultRegex);
  157. $this->_variables[$pos] = $name;
  158. } else {
  159. if (substr($part, 0, 1) === '@') {
  160. $this->_isTranslated = true;
  161. }
  162. $this->_parts[$pos] = $part;
  163. if ($part !== '*') {
  164. $this->_staticCount++;
  165. }
  166. }
  167. }
  168. }
  169. }
  170. /**
  171. * Matches a user submitted path with parts defined by a map. Assigns and
  172. * returns an array of variables on a successful match.
  173. *
  174. * @param string $path Path used to match against this routing map
  175. * @return array|false An array of assigned values or a false on a mismatch
  176. */
  177. public function match($path, $partial = false)
  178. {
  179. if ($this->_isTranslated) {
  180. $translateMessages = $this->getTranslator()->getMessages();
  181. }
  182. $pathStaticCount = 0;
  183. $values = array();
  184. $matchedPath = '';
  185. if (!$partial) {
  186. $path = trim($path, $this->_urlDelimiter);
  187. }
  188. if ($path !== '') {
  189. $path = explode($this->_urlDelimiter, $path);
  190. foreach ($path as $pos => $pathPart) {
  191. // Path is longer than a route, it's not a match
  192. if (!array_key_exists($pos, $this->_parts)) {
  193. if ($partial) {
  194. break;
  195. } else {
  196. return false;
  197. }
  198. }
  199. $matchedPath .= $pathPart . $this->_urlDelimiter;
  200. // If it's a wildcard, get the rest of URL as wildcard data and stop matching
  201. if ($this->_parts[$pos] == '*') {
  202. $count = count($path);
  203. for($i = $pos; $i < $count; $i+=2) {
  204. $var = urldecode($path[$i]);
  205. if (!isset($this->_wildcardData[$var]) && !isset($this->_defaults[$var]) && !isset($values[$var])) {
  206. $this->_wildcardData[$var] = (isset($path[$i+1])) ? urldecode($path[$i+1]) : null;
  207. }
  208. }
  209. break;
  210. }
  211. $name = isset($this->_variables[$pos]) ? $this->_variables[$pos] : null;
  212. $pathPart = urldecode($pathPart);
  213. // Translate value if required
  214. $part = $this->_parts[$pos];
  215. if ($this->_isTranslated && (substr($part, 0, 1) === '@' && $name === null) || $name !== null && in_array($name, $this->_translatable)) {
  216. if (substr($part, 0, 1) === '@') {
  217. $part = substr($part, 1);
  218. }
  219. if (($originalPathPart = array_search($pathPart, $translateMessages)) !== false) {
  220. $pathPart = $originalPathPart;
  221. }
  222. }
  223. // If it's a static part, match directly
  224. if ($name === null && $part != $pathPart) {
  225. return false;
  226. }
  227. // If it's a variable with requirement, match a regex. If not - everything matches
  228. if ($part !== null && !preg_match($this->_regexDelimiter . '^' . $part . '$' . $this->_regexDelimiter . 'iu', $pathPart)) {
  229. return false;
  230. }
  231. // If it's a variable store it's value for later
  232. if ($name !== null) {
  233. $values[$name] = $pathPart;
  234. } else {
  235. $pathStaticCount++;
  236. }
  237. }
  238. }
  239. // Check if all static mappings have been matched
  240. if ($this->_staticCount != $pathStaticCount) {
  241. return false;
  242. }
  243. $return = $values + $this->_wildcardData + $this->_defaults;
  244. // Check if all map variables have been initialized
  245. foreach ($this->_variables as $var) {
  246. if (!array_key_exists($var, $return)) {
  247. return false;
  248. }
  249. }
  250. $this->setMatchedPath(rtrim($matchedPath, $this->_urlDelimiter));
  251. $this->_values = $values;
  252. return $return;
  253. }
  254. /**
  255. * Assembles user submitted parameters forming a URL path defined by this route
  256. *
  257. * @param array $data An array of variable and value pairs used as parameters
  258. * @param boolean $reset Whether or not to set route defaults with those provided in $data
  259. * @return string Route path with user submitted parameters
  260. */
  261. public function assemble($data = array(), $reset = false, $encode = false)
  262. {
  263. if ($this->_isTranslated) {
  264. $translator = $this->getTranslator();
  265. if (isset($data['@locale'])) {
  266. $locale = $data['@locale'];
  267. unset($data['@locale']);
  268. } else {
  269. $locale = $this->getLocale();
  270. }
  271. }
  272. $url = array();
  273. $flag = false;
  274. foreach ($this->_parts as $key => $part) {
  275. $name = isset($this->_variables[$key]) ? $this->_variables[$key] : null;
  276. $useDefault = false;
  277. if (isset($name) && array_key_exists($name, $data) && $data[$name] === null) {
  278. $useDefault = true;
  279. }
  280. if (isset($name)) {
  281. if (isset($data[$name]) && !$useDefault) {
  282. $value = $data[$name];
  283. unset($data[$name]);
  284. } elseif (!$reset && !$useDefault && isset($this->_values[$name])) {
  285. $value = $this->_values[$name];
  286. } elseif (!$reset && !$useDefault && isset($this->_wildcardData[$name])) {
  287. $value = $this->_wildcardData[$name];
  288. } elseif (isset($this->_defaults[$name])) {
  289. $value = $this->_defaults[$name];
  290. } else {
  291. require_once 'Zend/Controller/Router/Exception.php';
  292. throw new Zend_Controller_Router_Exception($name . ' is not specified');
  293. }
  294. if ($this->_isTranslated && in_array($name, $this->_translatable)) {
  295. $url[$key] = $translator->translate($value, $locale);
  296. } else {
  297. $url[$key] = $value;
  298. }
  299. } elseif ($part != '*') {
  300. if ($this->_isTranslated && substr($part, 0, 1) === '@') {
  301. $url[$key] = $translator->translate(substr($part, 1), $locale);
  302. } else {
  303. $url[$key] = $part;
  304. }
  305. } else {
  306. if (!$reset) $data += $this->_wildcardData;
  307. foreach ($data as $var => $value) {
  308. if ($value !== null) {
  309. $url[$key++] = $var;
  310. $url[$key++] = $value;
  311. $flag = true;
  312. }
  313. }
  314. }
  315. }
  316. $return = '';
  317. foreach (array_reverse($url, true) as $key => $value) {
  318. $defaultValue = null;
  319. if (isset($this->_variables[$key])) {
  320. $defaultValue = $this->getDefault($this->_variables[$key]);
  321. if ($this->_isTranslated && $defaultValue !== null && isset($this->_translatable[$this->_variables[$key]])) {
  322. $defaultValue = $translator->translate($defaultValue, $locale);
  323. }
  324. }
  325. if ($flag || $value !== $defaultValue) {
  326. if ($encode) $value = urlencode($value);
  327. $return = $this->_urlDelimiter . $value . $return;
  328. $flag = true;
  329. }
  330. }
  331. return trim($return, $this->_urlDelimiter);
  332. }
  333. /**
  334. * Return a single parameter of route's defaults
  335. *
  336. * @param string $name Array key of the parameter
  337. * @return string Previously set default
  338. */
  339. public function getDefault($name) {
  340. if (isset($this->_defaults[$name])) {
  341. return $this->_defaults[$name];
  342. }
  343. return null;
  344. }
  345. /**
  346. * Return an array of defaults
  347. *
  348. * @return array Route defaults
  349. */
  350. public function getDefaults() {
  351. return $this->_defaults;
  352. }
  353. /**
  354. * Get all variables which are used by the route
  355. *
  356. * @return array
  357. */
  358. public function getVariables()
  359. {
  360. return $this->_variables;
  361. }
  362. /**
  363. * Set a default translator
  364. *
  365. * @param Zend_Translate $translator
  366. * @return void
  367. */
  368. public static function setDefaultTranslator(Zend_Translate $translator = null)
  369. {
  370. self::$_defaultTranslator = $translator;
  371. }
  372. /**
  373. * Get the default translator
  374. *
  375. * @return Zend_Translate
  376. */
  377. public static function getDefaultTranslator()
  378. {
  379. return self::$_defaultTranslator;
  380. }
  381. /**
  382. * Set a translator
  383. *
  384. * @param Zend_Translate $translator
  385. * @return void
  386. */
  387. public function setTranslator(Zend_Translate $translator)
  388. {
  389. $this->_translator = $translator;
  390. }
  391. /**
  392. * Get the translator
  393. *
  394. * @throws Zend_Controller_Router_Exception When no translator can be found
  395. * @return Zend_Translate
  396. */
  397. public function getTranslator()
  398. {
  399. if ($this->_translator !== null) {
  400. return $this->_translator;
  401. } else if (($translator = self::getDefaultTranslator()) !== null) {
  402. return $translator;
  403. } else {
  404. try {
  405. $translator = Zend_Registry::get('Zend_Translate');
  406. } catch (Zend_Exception $e) {
  407. $translator = null;
  408. }
  409. if ($translator instanceof Zend_Translate) {
  410. return $translator;
  411. }
  412. }
  413. require_once 'Zend/Controller/Router/Exception.php';
  414. throw new Zend_Controller_Router_Exception('Could not find a translator');
  415. }
  416. /**
  417. * Set a default locale
  418. *
  419. * @param mixed $locale
  420. * @return void
  421. */
  422. public static function setDefaultLocale($locale = null)
  423. {
  424. self::$_defaultLocale = $locale;
  425. }
  426. /**
  427. * Get the default locale
  428. *
  429. * @return mixed
  430. */
  431. public static function getDefaultLocale()
  432. {
  433. return self::$_defaultLocale;
  434. }
  435. /**
  436. * Set a locale
  437. *
  438. * @param mixed $locale
  439. * @return void
  440. */
  441. public function setLocale($locale)
  442. {
  443. $this->_locale = $locale;
  444. }
  445. /**
  446. * Get the locale
  447. *
  448. * @return mixed
  449. */
  450. public function getLocale()
  451. {
  452. if ($this->_locale !== null) {
  453. return $this->_locale;
  454. } else if (($locale = self::getDefaultLocale()) !== null) {
  455. return $locale;
  456. } else {
  457. try {
  458. $locale = Zend_Registry::get('Zend_Locale');
  459. } catch (Zend_Exception $e) {
  460. $locale = null;
  461. }
  462. if ($locale !== null) {
  463. return $locale;
  464. }
  465. }
  466. return null;
  467. }
  468. }