<?php
/**
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+ * DAMAGE.
*
- * This software consists of voluntary contributions made by many individuals
- * and is licensed under the MIT license.
+ * This software consists of voluntary contributions made by many
+ * individuals and is licensed under the MIT license.
*/
+
namespace PHPRouter;
class Route
{
$this->url = $resource;
$this->config = $config;
- $this->methods = isset($config['methods']) ? (array) $config['methods'] : array();
+ $this->methods = isset($config['methods']) ? (array)$config['methods'] : array();
$this->target = isset($config['target']) ? $config['target'] : null;
$this->name = isset($config['name']) ? $config['name'] : null;
$this->parameters = isset($config['parameters']) ? $config['parameters'] : array();
$this->parameters = $parameters;
}
- public function dispatch()
+ public function getValidRouteAction()
{
$action = explode('::', $this->config['_controller']);
+ $class = @$action[0];
+ $method = @$action[1];
+
+ if ( !class_exists($class)) {
+ return null;
+ }
+
+ $instance = new $class();
+
+ if (empty($action[1]) || trim($action[1]) === '') {
+ $method = "__invoke";
+ }
+
+ if ( !method_exists($instance, $method)) {
+ return null;
+ }
+
+ return $this->config['_controller'];
+ }
+
+ public function dispatch()
+ {
+ $action = explode('::', $this->config['_controller']);
$instance = new $action[0];
if ($this->parametersByName) {
$this->parameters = array($this->parameters);
}
+ ob_start();
+
if (empty($action[1]) || trim($action[1]) === '') {
+ // __invoke on a class
call_user_func_array($instance, $this->parameters);
-
- return ;
+ } else {
+ call_user_func_array(array($instance, $action[1]), $this->parameters);
}
- call_user_func_array(array($instance, $action[1]), $this->parameters);
+ $result = ob_get_clean();
+
+ return $result;
}
public function getAction()
<?php
/**
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+ * DAMAGE.
*
- * This software consists of voluntary contributions made by many individuals
- * and is licensed under the MIT license.
+ * This software consists of voluntary contributions made by many
+ * individuals and is licensed under the MIT license.
*/
+
namespace PHPRouter;
use Exception;
use Fig\Http\Message\RequestMethodInterface;
/**
- * Routing class to match request URL's against given routes and map them to a controller action.
+ * Routing class to match request URL's against given routes and map
+ * them to a controller action.
*/
class Router
{
}
}
- /**
- * Set the base _url - gets prepended to all route _url's.
- * @param $basePath
- */
- public function setBasePath($basePath)
- {
- $this->basePath = rtrim($basePath, '/');
- }
-
- /**
- * Matches the current request against mapped routes
- */
- public function matchCurrentRequest()
+ private function getRequestUrlAndMethod()
{
$requestMethod = (
isset($_POST['_method'])
$requestUrl = substr($requestUrl, 0, $pos);
}
- return $this->match($requestUrl, $requestMethod);
+ return array(
+ $requestMethod,
+ $requestUrl,
+ );
}
/**
- * Match given request _url and request method and see if a route has been defined for it
- * If so, return route's target
- * If called multiple times
+ * Set the base _url - gets prepended to all route _url's.
*
- * @param string $requestUrl
- * @param string $requestMethod
+ * @param $basePath
+ */
+ public function setBasePath($basePath)
+ {
+ $this->basePath = rtrim($basePath, '/');
+ }
+
+ /**
+ * check if the request has a valid route
*
- * @return bool|Route
+ * @return bool
*/
- public function match($requestUrl, $requestMethod = RequestMethodInterface::METHOD_GET)
+ public function requestHasValidRoute()
+ {
+ list($requestMethod, $requestUrl) = $this->getRequestUrlAndMethod();
+
+ /** @var Route $route */
+ list($route,) = $this->findRoute($requestUrl, $requestMethod);
+
+ if ($route === null) {
+ return false;
+ }
+
+ $action = $route->getValidRouteAction();
+
+ return $action !== null;
+ }
+
+ /**
+ * Matches the current request against mapped routes
+ */
+ public function matchCurrentRequest()
+ {
+ list($requestMethod, $requestUrl) = $this->getRequestUrlAndMethod();
+
+ return $this->match($requestUrl, $requestMethod);
+ }
+
+ private function findRoute($requestUrl, $requestMethod)
{
$currentDir = dirname($_SERVER['SCRIPT_NAME']);
+ $foundRoute = null;
+ $params = array();
foreach ($this->routes->all() as $routes) {
// compare server request method with route's allowed http methods
- if (! in_array($requestMethod, (array)$routes->getMethods(), true)) {
+ if ( !in_array($requestMethod, (array)$routes->getMethods(), true)) {
continue;
}
$requestUrl = str_replace($currentDir, '', $requestUrl);
}
- $route = rtrim($routes->getRegex(), '/');
+ $route = rtrim($routes->getRegex(), '/');
$pattern = '@^' . preg_quote($this->basePath) . $route . '/?$@i';
- if (!preg_match($pattern, $requestUrl, $matches)) {
+
+ if ( !preg_match($pattern, $requestUrl, $matches)) {
continue;
}
- $params = array();
-
if (preg_match_all('/:([\w-%]+)/', $routes->getUrl(), $argument_keys)) {
// grab array with matches
$argument_keys = $argument_keys[1];
// check arguments number
- if(count($argument_keys) !== (count($matches) -1)) {
+ if (count($argument_keys) !== (count($matches) - 1)) {
continue;
}
// loop trough parameter names, store matching value in $params array
foreach ($argument_keys as $key => $name) {
- if (isset($matches[$key+1])) {
- $params[$name] = $matches[$key+1];
+ if (isset($matches[$key + 1])) {
+ $params[$name] = $matches[$key + 1];
}
}
}
- $routes->setParameters($params);
- $routes->dispatch();
-
- return $routes;
+ $foundRoute = $routes;
+ break;
}
- return false;
+ /** @var Route $foundRoute */
+ /** @var array $params */
+ return array(
+ $foundRoute,
+ $params,
+ );
+ }
+
+ /**
+ * Match given request _url and request method and see if a route
+ * has been defined for it If so, return route's target If called
+ * multiple times
+ *
+ * @param string $requestUrl
+ * @param string $requestMethod
+ *
+ * @return bool|Route
+ */
+ public function match($requestUrl, $requestMethod = RequestMethodInterface::METHOD_GET)
+ {
+ /** @var Route $route */
+ list($route, $params) = $this->findRoute($requestUrl, $requestMethod);
+
+ if ($route !== null) {
+ $route->setParameters($params);
+ return $route->dispatch();
+ } else {
+ return;
+ }
}
/**
* Reverse route a named route
*
- * @param $routeName
+ * @param $routeName
* @param array $params Optional array of parameters to use in URL
*
* @throws Exception
public function generate($routeName, array $params = array())
{
// Check if route exists
- if (!isset($this->namedRoutes[$routeName])) {
+ if ( !isset($this->namedRoutes[$routeName])) {
throw new Exception("No route with the name $routeName has been found.");
}
/** @var \PHPRouter\Route $route */
$route = $this->namedRoutes[$routeName];
- $url = $route->getUrl();
+ $url = $route->getUrl();
// replace route url with given parameters
if ($params && preg_match_all('/:(\w+)/', $url, $param_keys)) {
// loop trough parameter names, store matching value in $params array
foreach ($param_keys as $key) {
if (isset($params[$key])) {
- $url = preg_replace('/:'.preg_quote($key,'/').'/', $params[$key], $url, 1);
+ $url = preg_replace('/:' . preg_quote($key, '/') . '/', $params[$key], $url, 1);
}
}
}
* Create routes by array, and return a Router object
*
* @param array $config provide by Config::loadFromFile()
+ *
* @return Router
*/
public static function parseConfig(array $config)
foreach ($config['routes'] as $name => $route) {
$collection->attachRoute(new Route($route[0], array(
'_controller' => str_replace('.', '::', $route[1]),
- 'methods' => $route[2],
- 'name' => $name
+ 'methods' => $route[2],
+ 'name' => $name,
)));
}