Back to ApiRouter class

Method parseApiRoute

public array
parseApiRoute
(mixed $method = 'GET')
Parse the given route and return the name of a controller mapped to the given route.
Parameters
  • string $method Request method to match. One of GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE or PATCH
Returns
  • array An array containing the controller and the matched variables.
Since
  • 4.0.0
-
  • \InvalidArgumentException
Class: ApiRouter
Project: Joomla

Method parseApiRoute - Source code

/**
 * Parse the given route and return the name of a controller mapped to the given route.
 *
 * @param   string  $method  Request method to match. One of GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE or PATCH
 *
 * @return  array   An array containing the controller and the matched variables.
 *
 * @since   4.0.0
 * @throws  \InvalidArgumentException
 */
public function parseApiRoute($method = 'GET')
{
    $method = strtoupper($method);
    $validMethods = ["GET", "POST", "PUT", "DELETE", "HEAD", "TRACE", "PATCH"];
    if (!\in_array($method, $validMethods)) {
        throw new \InvalidArgumentException(sprintf('%s is not a valid HTTP method.', $method));
    }
    // Get the path from the route and remove and leading or trailing slash.
    $routePath = $this->getRoutePath();
    $query = Uri::getInstance()->getQuery(true);
    // Iterate through all of the known routes looking for a match.
    foreach ($this->routes as $route) {
        if (\in_array($method, $route->getMethods())) {
            if (preg_match($route->getRegex(), ltrim($routePath, '/'), $matches)) {
                // If we have gotten this far then we have a positive match.
                $vars = $route->getDefaults();
                foreach ($route->getRouteVariables() as $i => $var) {
                    $vars[$var] = $matches[$i + 1];
                }
                $controller = preg_split("/[.]+/", $route->getController());
                $vars = array_merge($vars, $query);
                return ['controller' => $controller[0], 'task' => $controller[1], 'vars' => $vars];
            }
        }
    }
    throw new RouteNotFoundException(sprintf('Unable to handle request for route `%s`.', $routePath));
}