OSDN Git Service

e191a5dd5192f41064dea169bc8d5e4709081b25
[php-libraries/Router.git] / src / PHPRouter / Router.php
1 <?php
2 /**
3  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14  *
15  * This software consists of voluntary contributions made by many individuals
16  * and is licensed under the MIT license.
17  */
18 namespace PHPRouter;
19
20 use Exception;
21 use PHPRouter\RouteCollection;
22
23 /**
24  * Routing class to match request URL's against given routes and map them to a controller action.
25  */
26 class Router
27 {
28     /**
29      * Array that holds all Route objects
30      *
31      * @var array
32      */
33     private $routes = array();
34
35     /**
36      * Array to store named routes in, used for reverse routing.
37      * @var array
38      */
39     private $namedRoutes = array();
40
41     /**
42      * The base REQUEST_URI. Gets prepended to all route url's.
43      * @var string
44      */
45     private $basePath = '';
46
47     /**
48      * @param RouteCollection $collection
49      */
50     public function __construct(RouteCollection $collection)
51     {
52         $this->routes = $collection;
53     }
54
55     /**
56      * Set the base _url - gets prepended to all route _url's.
57      * @param $basePath
58      */
59     public function setBasePath($basePath)
60     {
61         $this->basePath = rtrim($basePath, '/');
62     }
63
64     /**
65      * Matches the current request against mapped routes
66      */
67     public function matchCurrentRequest()
68     {
69         $requestMethod = (
70             isset($_POST['_method'])
71             && ($_method = strtoupper($_POST['_method']))
72             && in_array($_method, array('PUT', 'DELETE'))
73         ) ? $_method : $_SERVER['REQUEST_METHOD'];
74
75         $requestUrl = $_SERVER['REQUEST_URI'];
76
77         // strip GET variables from URL
78         if (($pos = strpos($requestUrl, '?')) !== false) {
79             $requestUrl =  substr($requestUrl, 0, $pos);
80         }
81
82         return $this->match($requestUrl, $requestMethod);
83     }
84
85     /**
86      * Match given request _url and request method and see if a route has been defined for it
87      * If so, return route's target
88      * If called multiple times
89      *
90      * @param string $requestUrl
91      * @param string $requestMethod
92      *
93      * @return bool|Route
94      */
95     public function match($requestUrl, $requestMethod = 'GET')
96     {
97         foreach ($this->routes->all() as $routes) {
98
99             // compare server request method with route's allowed http methods
100             if (! in_array($requestMethod, (array) $routes->getMethods())) {
101                 continue;
102             }
103
104             $currentDir = dirname($_SERVER['SCRIPT_NAME']);
105             $requestUrl = str_replace($currentDir, '', $requestUrl);
106
107             // check if request _url matches route regex. if not, return false.
108             if (! preg_match("@^" . $this->basePath . $routes->getRegex() . "*$@i", $requestUrl, $matches)) {
109                 continue;
110             }
111
112             $params = array();
113
114             if (preg_match_all("/:([\w-%]+)/", $routes->getUrl(), $argument_keys)) {
115
116                 // grab array with matches
117                 $argument_keys = $argument_keys[1];
118
119                 // loop trough parameter names, store matching value in $params array
120                 foreach ($argument_keys as $key => $name) {
121                     if (isset($matches[$key + 1])) {
122                         $params[$name] = $matches[$key + 1];
123                     }
124                 }
125
126             }
127
128             $routes->setParameters($params);
129             $routes->dispatch();
130
131             return $routes;
132         }
133
134         return false;
135     }
136
137     /**
138      * Reverse route a named route
139      *
140      * @param $routeName
141      * @param array $params Optional array of parameters to use in URL
142      *
143      * @throws Exception
144      *
145      * @return string The url to the route
146      */
147     public function generate($routeName, array $params = array())
148     {
149         // Check if route exists
150         if (! isset($this->namedRoutes[$routeName])) {
151             throw new Exception("No route with the name $routeName has been found.");
152         }
153
154         /** @var \PHPRouter\Route $route */
155         $route = $this->namedRoutes[$routeName];
156         $url = $route->getUrl();
157
158         // replace route url with given parameters
159         if ($params && preg_match_all("/:(\w+)/", $url, $param_keys)) {
160             // grab array with matches
161             $param_keys = $param_keys[1];
162
163             // loop trough parameter names, store matching value in $params array
164             foreach ($param_keys as $key) {
165                 if (isset($params[$key])) {
166                     $url = preg_replace("/:(\w+)/", $params[$key], $url, 1);
167                 }
168             }
169         }
170
171         return $url;
172     }
173
174     /**
175      * Create routes by array, and return a Router object
176      *
177      * @param array $config provide by Config::loadFromFile()
178      * @return Router
179      */
180     public static function parseConfig(array $config)
181     {
182         $collection = new RouteCollection();
183         foreach ($config['routes'] as $name => $route) {
184             $collection->attachRoute(new Route($route[0], array(
185                 '_controller' => str_replace('.', '::', $route[1]),
186                 'methods' => $route[2]
187             )));
188         }
189
190         $router = new Router($collection);
191         if (isset($config['base_path'])) {
192             $router->setBasePath($config['base_path']);
193         }
194
195         return $router;
196     }
197 }