Router.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /**
  3. * Pimf
  4. *
  5. * @copyright Copyright (c) Gjero Krsteski (http://krsteski.de)
  6. * @license http://krsteski.de/new-bsd-license New BSD License
  7. */
  8. namespace Pimf;
  9. use Pimf\Route\Target;
  10. /**
  11. * Router
  12. *
  13. * This class is responsible for registering route objects, assigning names to route objects,
  14. * finding routes that match the current HTTP request, and creating URLs for a named route.
  15. *
  16. * @package Pimf
  17. * @author Gjero Krsteski <[email protected]>
  18. */
  19. class Router
  20. {
  21. /**
  22. * @var Route[]
  23. */
  24. protected $routes = array();
  25. public function __construct()
  26. {
  27. //it is a pimf-framework restriction.
  28. $this->map(new Route('/:controller'))->map(new Route('/:controller/:action'))->map(new Route('/:controller/:action/:id'));
  29. }
  30. /**
  31. * @param Route $route
  32. *
  33. * @return Router
  34. */
  35. public function map(Route $route)
  36. {
  37. $this->routes[$route->getRule()] = $route;
  38. return $this;
  39. }
  40. /**
  41. * @param Route $route
  42. *
  43. * @return Target
  44. */
  45. private function target(Route $route)
  46. {
  47. $params = $route->getParams();
  48. $target = new Target($params['controller']);
  49. unset($params['controller']);
  50. if (isset($params['action'])) {
  51. $target->setAction($params['action']);
  52. unset($params['action']);
  53. }
  54. $target->setParams($params);
  55. return $target;
  56. }
  57. /**
  58. * @return bool|Target
  59. */
  60. public function find()
  61. {
  62. // check custom routes first
  63. // than framework's restriction routes.
  64. foreach (array_reverse($this->routes) as $route) {
  65. if ($route->matches() === true) {
  66. return $this->target($route);
  67. }
  68. }
  69. return false;
  70. }
  71. }