Route.php 17 KB

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