This repository has been archived on 2024-06-26. You can view files and clone it, but cannot push or open issues or pull requests.
sakura/app/Router/Collection.php

93 lines
2.1 KiB
PHP
Raw Normal View History

2016-09-11 14:25:22 +00:00
<?php
/**
* Holds the Route Collection object.
* @package Sakura
*/
namespace Sakura\Router;
/**
* A route collection.
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Collection
{
/**
* Contains the path list associated with the routes.
* @var array
*/
private $paths = [];
/**
* Contains the names list associated with the routes.
* @var array
*/
private $names = [];
/**
* Add multiple routes.
* @param Route $routes
*/
public function add(Route...$routes)
{
foreach ($routes as $route) {
foreach ($route->methods as $method) {
$this->paths[$method][$route->path] = $route;
}
if ($route->name !== null) {
$this->names[$route->name] = $route;
}
foreach ($route->subroutes as $subroute) {
$subroute->setPath($route->path . '/' . $subroute->path);
if ($subroute->controller === null) {
$subroute->controller($route->controller);
}
$this->add($subroute);
}
$route->subroutes = null;
}
}
/**
* Resolve route by path and method.
2016-10-13 18:43:29 +00:00
* @param Request $request
2016-09-11 14:25:22 +00:00
* @return mixed
*/
2016-10-13 18:43:29 +00:00
public function resolve(Request $request)
2016-09-11 14:25:22 +00:00
{
2016-10-13 18:43:29 +00:00
$path = trim(parse_url($request->path, PHP_URL_PATH), '/');
2016-09-11 14:25:22 +00:00
2016-10-13 18:43:29 +00:00
if (!array_key_exists($request->method, $this->paths)
|| !array_key_exists($path, $this->paths[$request->method])) {
2016-09-16 19:06:09 +00:00
throw new \Exception;
2016-09-11 14:25:22 +00:00
}
2016-10-13 18:43:29 +00:00
return $this->paths[$request->method][$path]->fire();
2016-09-11 14:25:22 +00:00
}
/**
* Generate a route's url by name.
* @param string $name
* @param array $params
* @return string
*/
public function url($name, $params = [])
{
if (!array_key_exists($name, $this->names)) {
2016-09-21 11:26:08 +00:00
throw new \Exception;
2016-09-11 14:25:22 +00:00
}
2016-09-21 11:30:01 +00:00
if (count($params)) {
//
}
2016-09-11 14:25:22 +00:00
return parse_url('/' . $this->names[$name]->path, PHP_URL_PATH);
}
}