Route.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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-2015 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-2015 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. *
  78. * @var array
  79. */
  80. protected $_variables = array();
  81. /**
  82. * Holds Route patterns for all URL parts. In case of a variable it stores it's regex
  83. * requirement or null. In case of a static part, it holds only it's direct value.
  84. * In case of a wildcard, it stores an asterisk (*)
  85. *
  86. * @var array
  87. */
  88. protected $_parts = array();
  89. /**
  90. * Holds user submitted default values for route's variables. Name and value pairs.
  91. *
  92. * @var array
  93. */
  94. protected $_defaults = array();
  95. /**
  96. * Holds user submitted regular expression patterns for route's variables' values.
  97. * Name and value pairs.
  98. *
  99. * @var array
  100. */
  101. protected $_requirements = array();
  102. /**
  103. * Associative array filled on match() that holds matched path values
  104. * for given variable names.
  105. *
  106. * @var array
  107. */
  108. protected $_values = array();
  109. /**
  110. * Associative array filled on match() that holds wildcard variable
  111. * names and values.
  112. *
  113. * @var array
  114. */
  115. protected $_wildcardData = array();
  116. /**
  117. * Helper var that holds a count of route pattern's static parts
  118. * for validation
  119. *
  120. * @var int
  121. */
  122. protected $_staticCount = 0;
  123. public function getVersion()
  124. {
  125. return 1;
  126. }
  127. /**
  128. * Instantiates route based on passed Zend_Config structure
  129. *
  130. * @param Zend_Config $config Configuration object
  131. * @return Zend_Controller_Router_Route
  132. */
  133. public static function getInstance(Zend_Config $config)
  134. {
  135. $reqs = ($config->reqs instanceof Zend_Config) ? $config->reqs->toArray() : array();
  136. $defs = ($config->defaults instanceof Zend_Config) ? $config->defaults->toArray() : array();
  137. return new self($config->route, $defs, $reqs);
  138. }
  139. /**
  140. * Prepares the route for mapping by splitting (exploding) it
  141. * to a corresponding atomic parts. These parts are assigned
  142. * a position which is later used for matching and preparing values.
  143. *
  144. * @param string $route Map used to match with later submitted URL path
  145. * @param array $defaults Defaults for map variables with keys as variable names
  146. * @param array $reqs Regular expression requirements for variables (keys as variable names)
  147. * @param Zend_Translate $translator Translator to use for this instance
  148. * @param mixed|null $locale
  149. */
  150. public function __construct(
  151. $route, $defaults = array(), $reqs = array(), Zend_Translate $translator = null, $locale = null
  152. )
  153. {
  154. $route = trim($route, $this->_urlDelimiter);
  155. $this->_defaults = (array)$defaults;
  156. $this->_requirements = (array)$reqs;
  157. $this->_translator = $translator;
  158. $this->_locale = $locale;
  159. if ($route !== '') {
  160. foreach (explode($this->_urlDelimiter, $route) as $pos => $part) {
  161. if (substr($part, 0, 1) == $this->_urlVariable && substr($part, 1, 1) != $this->_urlVariable) {
  162. $name = substr($part, 1);
  163. if (substr($name, 0, 1) === '@' && substr($name, 1, 1) !== '@') {
  164. $name = substr($name, 1);
  165. $this->_translatable[] = $name;
  166. $this->_isTranslated = true;
  167. }
  168. $this->_parts[$pos] = (isset($reqs[$name]) ? $reqs[$name] : $this->_defaultRegex);
  169. $this->_variables[$pos] = $name;
  170. } else {
  171. if (substr($part, 0, 1) == $this->_urlVariable) {
  172. $part = substr($part, 1);
  173. }
  174. if (substr($part, 0, 1) === '@' && substr($part, 1, 1) !== '@') {
  175. $this->_isTranslated = true;
  176. }
  177. $this->_parts[$pos] = $part;
  178. if ($part !== '*') {
  179. $this->_staticCount++;
  180. }
  181. }
  182. }
  183. }
  184. }
  185. /**
  186. * Matches a user submitted path with parts defined by a map. Assigns and
  187. * returns an array of variables on a successful match.
  188. *
  189. * @param string $path Path used to match against this routing map
  190. * @param boolean $partial
  191. * @throws Zend_Controller_Router_Exception
  192. * @return array|false An array of assigned values or a false on a mismatch
  193. */
  194. public function match($path, $partial = false)
  195. {
  196. if ($this->_isTranslated) {
  197. $translateMessages = $this->getTranslator()->getMessages();
  198. }
  199. $pathStaticCount = 0;
  200. $values = array();
  201. $matchedPath = '';
  202. if (!$partial) {
  203. $path = trim($path, $this->_urlDelimiter);
  204. }
  205. if ($path !== '') {
  206. $path = explode($this->_urlDelimiter, $path);
  207. foreach ($path as $pos => $pathPart) {
  208. // Path is longer than a route, it's not a match
  209. if (!array_key_exists($pos, $this->_parts)) {
  210. if ($partial) {
  211. break;
  212. } else {
  213. return false;
  214. }
  215. }
  216. $matchedPath .= $pathPart . $this->_urlDelimiter;
  217. // If it's a wildcard, get the rest of URL as wildcard data and stop matching
  218. if ($this->_parts[$pos] == '*') {
  219. $count = count($path);
  220. for ($i = $pos; $i < $count; $i += 2) {
  221. $var = urldecode($path[$i]);
  222. if (!isset($this->_wildcardData[$var]) && !isset($this->_defaults[$var])
  223. && !isset($values[$var])
  224. ) {
  225. $this->_wildcardData[$var] = (isset($path[$i + 1])) ? urldecode($path[$i + 1]) : null;
  226. }
  227. }
  228. $matchedPath = implode($this->_urlDelimiter, $path);
  229. break;
  230. }
  231. $name = isset($this->_variables[$pos]) ? $this->_variables[$pos] : null;
  232. $pathPart = urldecode($pathPart);
  233. // Translate value if required
  234. $part = $this->_parts[$pos];
  235. if ($this->_isTranslated
  236. && (substr($part, 0, 1) === '@' && substr($part, 1, 1) !== '@'
  237. && $name === null)
  238. || $name !== null && in_array($name, $this->_translatable)
  239. ) {
  240. if (substr($part, 0, 1) === '@') {
  241. $part = substr($part, 1);
  242. }
  243. if (($originalPathPart = array_search($pathPart, $translateMessages)) !== false) {
  244. $pathPart = $originalPathPart;
  245. }
  246. }
  247. if (substr($part, 0, 2) === '@@') {
  248. $part = substr($part, 1);
  249. }
  250. // If it's a static part, match directly
  251. if ($name === null && $part != $pathPart) {
  252. return false;
  253. }
  254. // If it's a variable with requirement, match a regex. If not - everything matches
  255. if ($part !== null
  256. && !preg_match(
  257. $this->_regexDelimiter . '^' . $part . '$' . $this->_regexDelimiter . 'iu', $pathPart
  258. )
  259. ) {
  260. return false;
  261. }
  262. // If it's a variable store it's value for later
  263. if ($name !== null) {
  264. $values[$name] = $pathPart;
  265. } else {
  266. $pathStaticCount++;
  267. }
  268. }
  269. }
  270. // Check if all static mappings have been matched
  271. if ($this->_staticCount != $pathStaticCount) {
  272. return false;
  273. }
  274. $return = $values + $this->_wildcardData + $this->_defaults;
  275. // Check if all map variables have been initialized
  276. foreach ($this->_variables as $var) {
  277. if (!array_key_exists($var, $return)) {
  278. return false;
  279. } elseif ($return[$var] == '' || $return[$var] === null) {
  280. // Empty variable? Replace with the default value.
  281. $return[$var] = $this->_defaults[$var];
  282. }
  283. }
  284. $this->setMatchedPath(rtrim($matchedPath, $this->_urlDelimiter));
  285. $this->_values = $values;
  286. return $return;
  287. }
  288. /**
  289. * Assembles user submitted parameters forming a URL path defined by this route
  290. *
  291. * @param array $data An array of variable and value pairs used as parameters
  292. * @param boolean $reset Whether or not to set route defaults with those provided in $data
  293. * @param boolean $encode
  294. * @param boolean $partial
  295. * @throws Zend_Controller_Router_Exception
  296. * @return string Route path with user submitted parameters
  297. */
  298. public function assemble($data = array(), $reset = false, $encode = false, $partial = false)
  299. {
  300. if ($this->_isTranslated) {
  301. $translator = $this->getTranslator();
  302. if (isset($data['@locale'])) {
  303. $locale = $data['@locale'];
  304. unset($data['@locale']);
  305. } else {
  306. $locale = $this->getLocale();
  307. }
  308. }
  309. $url = array();
  310. $flag = false;
  311. foreach ($this->_parts as $key => $part) {
  312. $name = isset($this->_variables[$key]) ? $this->_variables[$key] : null;
  313. $useDefault = false;
  314. if (isset($name) && array_key_exists($name, $data) && $data[$name] === null) {
  315. $useDefault = true;
  316. }
  317. if (isset($name)) {
  318. if (isset($data[$name]) && !$useDefault) {
  319. $value = $data[$name];
  320. unset($data[$name]);
  321. } elseif (!$reset && !$useDefault && isset($this->_values[$name])) {
  322. $value = $this->_values[$name];
  323. } elseif (!$reset && !$useDefault && isset($this->_wildcardData[$name])) {
  324. $value = $this->_wildcardData[$name];
  325. } elseif (array_key_exists($name, $this->_defaults)) {
  326. $value = $this->_defaults[$name];
  327. } else {
  328. require_once 'Zend/Controller/Router/Exception.php';
  329. throw new Zend_Controller_Router_Exception($name . ' is not specified');
  330. }
  331. if ($this->_isTranslated && in_array($name, $this->_translatable)) {
  332. $url[$key] = $translator->translate($value, $locale);
  333. } else {
  334. $url[$key] = $value;
  335. }
  336. } elseif ($part != '*') {
  337. if ($this->_isTranslated && substr($part, 0, 1) === '@') {
  338. if (substr($part, 1, 1) !== '@') {
  339. $url[$key] = $translator->translate(substr($part, 1), $locale);
  340. } else {
  341. $url[$key] = substr($part, 1);
  342. }
  343. } else {
  344. if (substr($part, 0, 2) === '@@') {
  345. $part = substr($part, 1);
  346. }
  347. $url[$key] = $part;
  348. }
  349. } else {
  350. if (!$reset) {
  351. $data += $this->_wildcardData;
  352. }
  353. $defaults = $this->getDefaults();
  354. foreach ($data as $var => $value) {
  355. if ($value !== null && (!isset($defaults[$var]) || $value != $defaults[$var])) {
  356. $url[$key++] = $var;
  357. $url[$key++] = $value;
  358. $flag = true;
  359. }
  360. }
  361. }
  362. }
  363. $return = '';
  364. foreach (array_reverse($url, true) as $key => $value) {
  365. $defaultValue = null;
  366. if (isset($this->_variables[$key])) {
  367. $defaultValue = $this->getDefault($this->_variables[$key]);
  368. if ($this->_isTranslated && $defaultValue !== null
  369. && isset($this->_translatable[$this->_variables[$key]])
  370. ) {
  371. $defaultValue = $translator->translate($defaultValue, $locale);
  372. }
  373. }
  374. if ($flag || $value !== $defaultValue || $partial) {
  375. if ($encode) {
  376. $value = urlencode($value);
  377. }
  378. $return = $this->_urlDelimiter . $value . $return;
  379. $flag = true;
  380. }
  381. }
  382. return trim($return, $this->_urlDelimiter);
  383. }
  384. /**
  385. * Return a single parameter of route's defaults
  386. *
  387. * @param string $name Array key of the parameter
  388. * @return string Previously set default
  389. */
  390. public function getDefault($name)
  391. {
  392. if (isset($this->_defaults[$name])) {
  393. return $this->_defaults[$name];
  394. }
  395. return null;
  396. }
  397. /**
  398. * Return an array of defaults
  399. *
  400. * @return array Route defaults
  401. */
  402. public function getDefaults()
  403. {
  404. return $this->_defaults;
  405. }
  406. /**
  407. * Get all variables which are used by the route
  408. *
  409. * @return array
  410. */
  411. public function getVariables()
  412. {
  413. return $this->_variables;
  414. }
  415. /**
  416. * Set a default translator
  417. *
  418. * @param Zend_Translate $translator
  419. * @return void
  420. */
  421. public static function setDefaultTranslator(Zend_Translate $translator = null)
  422. {
  423. self::$_defaultTranslator = $translator;
  424. }
  425. /**
  426. * Get the default translator
  427. *
  428. * @return Zend_Translate
  429. */
  430. public static function getDefaultTranslator()
  431. {
  432. return self::$_defaultTranslator;
  433. }
  434. /**
  435. * Set a translator
  436. *
  437. * @param Zend_Translate $translator
  438. * @return void
  439. */
  440. public function setTranslator(Zend_Translate $translator)
  441. {
  442. $this->_translator = $translator;
  443. }
  444. /**
  445. * Get the translator
  446. *
  447. * @throws Zend_Controller_Router_Exception When no translator can be found
  448. * @return Zend_Translate
  449. */
  450. public function getTranslator()
  451. {
  452. if ($this->_translator !== null) {
  453. return $this->_translator;
  454. } else {
  455. if (($translator = self::getDefaultTranslator()) !== null) {
  456. return $translator;
  457. } else {
  458. try {
  459. $translator = Zend_Registry::get('Zend_Translate');
  460. } catch (Zend_Exception $e) {
  461. $translator = null;
  462. }
  463. if ($translator instanceof Zend_Translate) {
  464. return $translator;
  465. }
  466. }
  467. }
  468. require_once 'Zend/Controller/Router/Exception.php';
  469. throw new Zend_Controller_Router_Exception('Could not find a translator');
  470. }
  471. /**
  472. * Set a default locale
  473. *
  474. * @param mixed $locale
  475. * @return void
  476. */
  477. public static function setDefaultLocale($locale = null)
  478. {
  479. self::$_defaultLocale = $locale;
  480. }
  481. /**
  482. * Get the default locale
  483. *
  484. * @return mixed
  485. */
  486. public static function getDefaultLocale()
  487. {
  488. return self::$_defaultLocale;
  489. }
  490. /**
  491. * Set a locale
  492. *
  493. * @param mixed $locale
  494. * @return void
  495. */
  496. public function setLocale($locale)
  497. {
  498. $this->_locale = $locale;
  499. }
  500. /**
  501. * Get the locale
  502. *
  503. * @return mixed
  504. */
  505. public function getLocale()
  506. {
  507. if ($this->_locale !== null) {
  508. return $this->_locale;
  509. } else {
  510. if (($locale = self::getDefaultLocale()) !== null) {
  511. return $locale;
  512. } else {
  513. try {
  514. $locale = Zend_Registry::get('Zend_Locale');
  515. } catch (Zend_Exception $e) {
  516. $locale = null;
  517. }
  518. if ($locale !== null) {
  519. return $locale;
  520. }
  521. }
  522. }
  523. return null;
  524. }
  525. }