/** * Decorates an URL with url context and query. * * @param string $url Relative URL * @param array $parameters An array of parameters * @param bool|string $referenceType The type of reference to be generated (one of the constants) * * @return string * * @throws \RuntimeException */ protected function decorateUrl($url, array $parameters = array(), $referenceType = self::ABSOLUTE_PATH) { if (!$this->context) { throw new \RuntimeException('No context associated to the CmsPageRouter'); } $schemeAuthority = ''; if ($this->context->getHost() && (self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType)) { $port = ''; if ('http' === $this->context->getScheme() && 80 != $this->context->getHttpPort()) { $port = sprintf(':%s', $this->context->getHttpPort()); } elseif ('https' === $this->context->getScheme() && 443 != $this->context->getHttpsPort()) { $port = sprintf(':%s', $this->context->getHttpsPort()); } $schemeAuthority = self::NETWORK_PATH === $referenceType ? '//' : sprintf('%s://', $this->context->getScheme()); $schemeAuthority = sprintf('%s%s%s', $schemeAuthority, $this->context->getHost(), $port); } if (self::RELATIVE_PATH === $referenceType) { $url = $this->getRelativePath($this->context->getPathInfo(), $url); } else { $url = sprintf('%s%s%s', $schemeAuthority, $this->context->getBaseUrl(), $url); } if (count($parameters) > 0) { return sprintf('%s?%s', $url, http_build_query($parameters, '', '&')); } return $url; }
public function action(RouterInterface $router, RequestContext $context) { $request = Request::createFromGlobals(); $bPath = $context->getPathInfo(); try { $parameters = $router->match($bPath); var_dump($parameters); $_controller = $parameters["_controller"]; $_controller = explode(":", $_controller); $class = $_controller[0]; $action = strtolower($_controller[1]) . "Action"; $class = new $class(); ob_start(); if (method_exists($class, $action)) { $class->{$action}($request, new JsonResponse()); $response = new Response(ob_get_clean()); } else { $response = new Response('Not Found', 404); } } catch (ResourceNotFoundException $e) { $response = new Response('Not Found', 404); } catch (Exception $e) { $response = new Response('An error occurred', 500); } $response->send(); }
public function generateI18nRouteFromCurrentRequest($culture, $referenceType = self::ABSOLUTE_PATH, $scheme = null) { $result = $this->match($this->context->getPathInfo(), $this->context->getHost(), $this->context->getScheme(), $this->context->getMethod()); $route = $result['_route']; if (strpos($route, ':i18n:') != false) { list(, , $route) = explode(':', $route, 3); } $result['_culture'] = $culture; unset($result['_route']); $parameters = new ArrayObject($result); $this->eventDispatcher->dispatch('Routing.preGenrateI18nRouteFromCurrentRequest', $this, compact('culture', 'referenceType', 'scheme', 'parameters')); return $this->generate($route, $parameters->getArrayCopy(), $referenceType, $scheme); }
/** * {@inheritdoc} */ public function build(RouteMatchInterface $route_match) { $links = array(); // General path-based breadcrumbs. Use the actual request path, prior to // resolving path aliases, so the breadcrumb can be defined by simply // creating a hierarchy of path aliases. $path = trim($this->context->getPathInfo(), '/'); $path_elements = explode('/', $path); $exclude = array(); // Don't show a link to the front-page path. $front = $this->config->get('page.front'); $exclude[$front] = TRUE; // /user is just a redirect, so skip it. // @todo Find a better way to deal with /user. $exclude['user'] = TRUE; while (count($path_elements) > 1) { array_pop($path_elements); // Copy the path elements for up-casting. $route_request = $this->getRequestForPath(implode('/', $path_elements), $exclude); if ($route_request) { $route_name = $route_request->attributes->get(RouteObjectInterface::ROUTE_NAME); // Note that the parameters don't really matter here since we're // passing in the request which already has the upcast attributes. $parameters = array(); $access = $this->accessManager->checkNamedRoute($route_name, $parameters, $this->currentUser, $route_request); if ($access) { $title = $this->titleResolver->getTitle($route_request, $route_request->attributes->get(RouteObjectInterface::ROUTE_OBJECT)); } if ($access) { if (!isset($title)) { // Fallback to using the raw path component as the title if the // route is missing a _title or _title_callback attribute. $title = str_replace(array('-', '_'), ' ', Unicode::ucfirst(end($path_elements))); } // @todo Replace with a #type => link render element so that the alter // hook can work with the actual data. $links[] = $this->l($title, $route_request->attributes->get(RouteObjectInterface::ROUTE_NAME), $route_request->attributes->get('_raw_variables')->all(), array('html' => TRUE)); } } } if ($path && $path != $front) { // Add the Home link, except for the front page. $links[] = $this->l($this->t('Home'), '<front>'); } return array_reverse($links); }
/** * @param string $pathInfo * @param bool|string $referenceType * * @return string */ protected function getUrlOrPathForType($pathInfo, $referenceType) { $url = $pathInfo; $scheme = $this->context->getScheme(); if (self::NETWORK_PATH !== $referenceType && ($scheme === 'http' && $this->sslEnabled === true || $scheme === 'https' && $this->sslEnabled === false)) { $referenceType = self::ABSOLUTE_URL; } switch ($referenceType) { case self::ABSOLUTE_URL: case self::NETWORK_PATH: $url = $this->buildUrl($pathInfo, $referenceType); break; case self::ABSOLUTE_PATH: $url = $pathInfo; break; case self::RELATIVE_PATH: $url = UrlGenerator::getRelativePath($this->context->getPathInfo(), $pathInfo); break; } return $url; }
public function testFromRequest() { $request = Request::create('https://test.com:444/foo?bar=baz'); $requestContext = new RequestContext(); $requestContext->setHttpPort(123); $requestContext->fromRequest($request); $this->assertEquals('', $requestContext->getBaseUrl()); $this->assertEquals('GET', $requestContext->getMethod()); $this->assertEquals('test.com', $requestContext->getHost()); $this->assertEquals('https', $requestContext->getScheme()); $this->assertEquals('/foo', $requestContext->getPathInfo()); $this->assertEquals('bar=baz', $requestContext->getQueryString()); $this->assertSame(123, $requestContext->getHttpPort()); $this->assertSame(444, $requestContext->getHttpsPort()); $request = Request::create('http://test.com:8080/foo?bar=baz'); $requestContext = new RequestContext(); $requestContext->setHttpsPort(567); $requestContext->fromRequest($request); $this->assertSame(8080, $requestContext->getHttpPort()); $this->assertSame(567, $requestContext->getHttpsPort()); }
/** * @throws MissingMandatoryParametersException When some parameters are missing that are mandatory for the route * @throws InvalidParameterException When a parameter value for a placeholder is not correct because * it does not match the requirement */ protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, array $requiredSchemes = array()) { $variables = array_flip($variables); $mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters); // all params must be given if ($diff = array_diff_key($variables, $mergedParams)) { throw new MissingMandatoryParametersException(sprintf('Some mandatory parameters are missing ("%s") to generate a URL for route "%s".', implode('", "', array_keys($diff)), $name)); } $url = ''; $optional = true; foreach ($tokens as $token) { if ('variable' === $token[0]) { if (!$optional || !array_key_exists($token[3], $defaults) || null !== $mergedParams[$token[3]] && (string) $mergedParams[$token[3]] !== (string) $defaults[$token[3]]) { // check requirement if (null !== $this->strictRequirements && !preg_match('#^' . $token[2] . '$#', $mergedParams[$token[3]])) { $message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]); if ($this->strictRequirements) { throw new InvalidParameterException($message); } if ($this->logger) { $this->logger->error($message); } return; } $url = $token[1] . $mergedParams[$token[3]] . $url; $optional = false; } } else { // static text $url = $token[1] . $url; $optional = false; } } if ('' === $url) { $url = '/'; } // the contexts base URL is already encoded (see Symfony\Component\HttpFoundation\Request) $url = strtr(rawurlencode($url), $this->decodedChars); // the path segments "." and ".." are interpreted as relative reference when resolving a URI; see http://tools.ietf.org/html/rfc3986#section-3.3 // so we need to encode them as they are not used for this purpose here // otherwise we would generate a URI that, when followed by a user agent (e.g. browser), does not match this route $url = strtr($url, array('/../' => '/%2E%2E/', '/./' => '/%2E/')); if ('/..' === substr($url, -3)) { $url = substr($url, 0, -2) . '%2E%2E'; } elseif ('/.' === substr($url, -2)) { $url = substr($url, 0, -1) . '%2E'; } $schemeAuthority = ''; if ($host = $this->context->getHost()) { $scheme = $this->context->getScheme(); if ($requiredSchemes) { $schemeMatched = false; foreach ($requiredSchemes as $requiredScheme) { if ($scheme === $requiredScheme) { $schemeMatched = true; break; } } if (!$schemeMatched) { $referenceType = self::ABSOLUTE_URL; $scheme = current($requiredSchemes); } } elseif (isset($requirements['_scheme']) && ($req = strtolower($requirements['_scheme'])) && $scheme !== $req) { // We do this for BC; to be removed if _scheme is not supported anymore $referenceType = self::ABSOLUTE_URL; $scheme = $req; } if ($hostTokens) { $routeHost = ''; foreach ($hostTokens as $token) { if ('variable' === $token[0]) { if (null !== $this->strictRequirements && !preg_match('#^' . $token[2] . '$#i', $mergedParams[$token[3]])) { $message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]); if ($this->strictRequirements) { throw new InvalidParameterException($message); } if ($this->logger) { $this->logger->error($message); } return; } $routeHost = $token[1] . $mergedParams[$token[3]] . $routeHost; } else { $routeHost = $token[1] . $routeHost; } } if ($routeHost !== $host) { $host = $routeHost; if (self::ABSOLUTE_URL !== $referenceType) { $referenceType = self::NETWORK_PATH; } } } if (self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType) { $port = ''; if ('http' === $scheme && 80 != $this->context->getHttpPort()) { $port = ':' . $this->context->getHttpPort(); } elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) { $port = ':' . $this->context->getHttpsPort(); } $schemeAuthority = self::NETWORK_PATH === $referenceType ? '//' : "{$scheme}://"; $schemeAuthority .= $host . $port; } } if (self::RELATIVE_PATH === $referenceType) { $url = self::getRelativePath($this->context->getPathInfo(), $url); } else { $url = $schemeAuthority . $this->context->getBaseUrl() . $url; } // add a query string if needed $extra = array_diff_key($parameters, $variables, $defaults); if ($extra && ($query = http_build_query($extra, '', '&'))) { // "/" and "?" can be left decoded for better user experience, see // http://tools.ietf.org/html/rfc3986#section-3.4 $url .= '?' . strtr($query, array('%2F' => '/')); } return $url; }