/** * Sets the scheme and host overrides (if any) on the RequestContext. * * This needs to happen after RouterListener as that sets the scheme * and host from the request. To override we need to be after that. * * @param GetResponseEvent $event */ public function onRequest(GetResponseEvent $event) { if (!$this->override) { return; } $override = $this->override; // Prepend scheme if not included so parse_url doesn't choke. if (strpos($override, 'http') !== 0) { $override = 'http://' . $override; } $parts = parse_url($override); // Only override scheme if it's an upgrade to https. // i.e Don't do: https -> http if (isset($parts['scheme']) && $parts['scheme'] === 'https') { $this->requestContext->setScheme($parts['scheme']); } if (isset($parts['host'])) { $this->requestContext->setHost($parts['host']); } }
public function buildContext(RequestContext $context) { $context->setScheme($this->scheme); if ($this->host && trim($this->host) !== '') { $context->setHost($this->host); } parent::setContext($context); }
/** * @dataProvider getPortData */ public function testPort($defaultHttpPort, $defaultHttpsPort, $uri, $expectedHttpPort, $expectedHttpsPort) { $listener = new RouterListener($this->router, $defaultHttpPort, $defaultHttpsPort); $expectedContext = new RequestContext(); $expectedContext->setHttpPort($expectedHttpPort); $expectedContext->setHttpsPort($expectedHttpsPort); $expectedContext->setScheme(0 === strpos($uri, 'https') ? 'https' : 'http'); $this->router->expects($this->once())->method('setContext')->with($expectedContext); $event = $this->createGetResponseEventForUri($uri); $listener->onEarlyCoreRequest($event); }
public function testGenerateDoesUseCorrectHostWhenSchemeChanges() { $router = $this->getRouter(); $router->setHostMap(array('en' => 'en.test', 'de' => 'de.test')); $context = new RequestContext(); $context->setScheme('http'); $context->setParameter('_locale', 'en'); $router->setContext($context); $this->assertEquals('https://en.test/login', $router->generate('login')); $this->assertEquals('https://de.test/einloggen', $router->generate('login', array('_locale' => 'de'))); }
public function testNonStandHttpsRedirect() { $coll = new RouteCollection(); $coll->add('foo', new Route('/foo', array(), array('_scheme' => 'https'))); $context = new RequestContext(); $context->setHttpsPort(9000); $context->setScheme('http'); $matcher = new UrlMatcher($coll, $context); $result = $matcher->match('/foo'); $this->assertArrayHasKey('url', $result); $this->assertSame($result['url'], 'https://localhost:9000/foo'); }
public function testHowToForceScheme() { $router = $this->container->get('router'); $collection = new RouteCollection(); $collection->add('routeA', new Route('/routeA'), array(), array('_scheme' => 'http')); $collection->add('routeB', new Route('/routeB', array(), array('_scheme' => 'https'))); $router->setCollection($collection); // WARNING: There is ONLY one case where without passing the third argument the router generate an URL, when the current // scheme is different from the target route (http -> https). $context = new RequestContext(); $context->setScheme('http'); $router->setContext($context); $this->assertEquals('https://localhost/routeB', $router->generate('routeB', array())); $context = new RequestContext(); $context->setScheme('https'); $router->setContext($context); $this->assertEquals('http://localhost/routeA', $router->generate('routeA', array()), "BUG: This case failed because only _scheme is warmup (in apptestUrlGenerator) only when _scheme is https. This should be the case also for http"); }
public function generate($name, array $parameters = array(), $referenceType = self::ABSOLUTE_PATH, $scheme = null) { $contextParameters = array_deep_merge($this->sessionDefaultParameters, $this->defaultParameters, $this->context->getParameters()); $oldContextParameters = $this->context->getParameters(); $this->context->setParameters($contextParameters); $oldScheme = null; if ($scheme) { $oldScheme = $this->context->getScheme(); $this->context->setScheme($scheme); } $oldHost = $this->context->getHost(); $context = $this->context; $finalize = new OutOfScopeFinalize(function () use($oldContextParameters, $oldScheme, $oldHost, $context, $scheme) { if ($scheme) { $context->setScheme($oldScheme); } $context->setHost($oldHost); $context->setParameters($oldContextParameters); }); $cultures = $this->getCultures(array_merge($contextParameters, $parameters)); $route = null; foreach ($cultures as $culture) { $routeName = $this->getI18nRouteName($name, $culture); if ($this->routeCollection->get($routeName)) { try { $host = $this->getHostForCulture($culture == '' ? 'default' : $culture); $this->context->setHost($host); if ($host != $oldHost) { $referenceType = self::ABSOLUTE_URL; } } catch (NoHostFoundForCultureException $e) { //We do nothing with the exception, it will use the request domain } $route = $this->urlGenerator->generate($routeName, $parameters, $referenceType); break; } } if (is_null($route)) { $route = $this->urlGenerator->generate($name, $parameters); } return $route; }
public function testComposeSchemaHttpsAndCustomPortAndFileUrlOnResolve() { $requestContext = new RequestContext(); $requestContext->setScheme('https'); $requestContext->setHost('thehost'); $requestContext->setHttpsPort(444); $resolver = new WebPathResolver($this->createFilesystemMock(), $requestContext, '/aWebRoot', 'aCachePrefix'); $this->assertEquals('https://thehost:444/aCachePrefix/aFilter/aPath', $resolver->resolve('aPath', 'aFilter')); }
/** * Generate a URL to a route * * @param string $route Name of the route to travel * @param array $params String or array of additional url parameters * @param bool $is_amp Is url using & (true) or & (false) * @param string|bool $session_id Possibility to use a custom session id instead of the global one * @param bool|string $reference_type The type of reference to be generated (one of the constants) * @return string The URL already passed through append_sid() */ public function route($route, array $params = array(), $is_amp = true, $session_id = false, $reference_type = UrlGeneratorInterface::ABSOLUTE_PATH) { $anchor = ''; if (isset($params['#'])) { $anchor = '#' . $params['#']; unset($params['#']); } $context = new RequestContext(); $context->fromRequest($this->symfony_request); if ($this->config['force_server_vars']) { $context->setHost($this->config['server_name']); $context->setScheme(substr($this->config['server_protocol'], 0, -3)); $context->setHttpPort($this->config['server_port']); $context->setHttpsPort($this->config['server_port']); $context->setBaseUrl(rtrim($this->config['script_path'], '/')); } $script_name = $this->symfony_request->getScriptName(); $page_name = substr($script_name, -1, 1) == '/' ? '' : utf8_basename($script_name); $base_url = $context->getBaseUrl(); // Append page name if base URL does not contain it if (!empty($page_name) && strpos($base_url, '/' . $page_name) === false) { $base_url .= '/' . $page_name; } // If enable_mod_rewrite is false we need to replace the current front-end by app.php, otherwise we need to remove it. $base_url = str_replace('/' . $page_name, empty($this->config['enable_mod_rewrite']) ? '/app.' . $this->php_ext : '', $base_url); // We need to update the base url to move to the directory of the app.php file if the current script is not app.php if ($page_name !== 'app.php' && !$this->config['force_server_vars']) { if (empty($this->config['enable_mod_rewrite'])) { $base_url = str_replace('/app.' . $this->php_ext, '/' . $this->phpbb_root_path . 'app.' . $this->php_ext, $base_url); } else { $base_url .= preg_replace(get_preg_expression('path_remove_dot_trailing_slash'), '$2', $this->phpbb_root_path); } } $base_url = $this->request->escape($this->filesystem->clean_path($base_url), true); $context->setBaseUrl($base_url); $this->router->setContext($context); $route_url = $this->router->generate($route, $params, $reference_type); if ($is_amp) { $route_url = str_replace(array('&', '&'), array('&', '&'), $route_url); } if ($reference_type === UrlGeneratorInterface::RELATIVE_PATH && empty($this->config['enable_mod_rewrite'])) { $route_url = 'app.' . $this->php_ext . '/' . $route_url; } return append_sid($route_url . $anchor, false, $is_amp, $session_id, true); }
/** * Tests that the context is not modified if the hostname is set. * * To tests this case, we omit the _ssl parameter and set the scheme to "https" in the context. If the * generator still returns a HTTPS URL, we know that the context has not been modified. */ public function testContextNotModifiedIfHostnameIsSet() { $routes = new RouteCollection(); $routes->add('contao_index', new Route('/')); $context = new RequestContext(); $context->setHost('contao.org'); $context->setScheme('https'); $generator = new UrlGenerator(new ParentUrlGenerator($routes, $context), $this->mockContaoFramework(), false); $this->assertEquals('https://contao.org/', $generator->generate('index', ['_domain' => 'contao.org'], UrlGeneratorInterface::ABSOLUTE_URL)); }
/** * Call match on ChainRouter that has RequestMatcher in the chain. * * @dataProvider provideBaseUrl */ public function testMatchWithRequestMatchersAndContext($baseUrl) { $url = '//test'; list($low) = $this->createRouterMocks(); $high = $this->getMock('Symfony\\Cmf\\Component\\Routing\\Tests\\Routing\\RequestMatcher'); $high->expects($this->once())->method('matchRequest')->with($this->callback(function (Request $r) use($url, $baseUrl) { return true === $r->isSecure() && 'foobar.com' === $r->getHost() && 4433 === $r->getPort() && $baseUrl === $r->getBaseUrl() && $url === $r->getPathInfo(); }))->will($this->throwException(new \Symfony\Component\Routing\Exception\ResourceNotFoundException())); $low->expects($this->once())->method('match')->with($url)->will($this->returnValue(array('test'))); $this->router->add($low, 10); $this->router->add($high, 20); $requestContext = new RequestContext(); $requestContext->setScheme('https'); $requestContext->setHost('foobar.com'); $requestContext->setHttpsPort(4433); $requestContext->setBaseUrl($baseUrl); $this->router->setContext($requestContext); $result = $this->router->match($url); $this->assertEquals(array('test'), $result); }
public function testScheme() { $requestContext = new RequestContext(); $requestContext->setScheme('HTTPS'); $this->assertSame('https', $requestContext->getScheme()); }
/** * @param $url * @param RequestContext $context * @return array */ private function setUrlInContext($url, RequestContext $context) { $parts = parse_url($url); if (false === (bool) $parts) { throw new \RuntimeException('Invalid Application URL configured. Unable to generate links'); } if (isset($parts['schema'])) { $context->setScheme($parts['schema']); } if (isset($parts['host'])) { $context->setHost($parts['host']); } if (isset($parts['port'])) { $context->setHttpPort($parts['port']); $context->setHttpsPort($parts['port']); } if (isset($parts['path'])) { $context->setBaseUrl(rtrim($parts['path'], '/')); } if (isset($parts['query'])) { $context->setQueryString($parts['query']); } }
/** * @dataProvider providerGenerateWithSiteAccess * * @param string $urlGenerated The URL generated by the standard UrLGenerator * @param string $relevantUri The relevant URI part of the generated URL (without host and basepath) * @param string $expectedUrl The URL we're expecting to be finally generated, with siteaccess * @param string $saName The SiteAccess name * @param bool $isMatcherLexer True if the siteaccess matcher is URILexer * @param bool $absolute True if generated link needs to be absolute * @param string $routeName */ public function testGenerateWithSiteAccess($urlGenerated, $relevantUri, $expectedUrl, $saName, $isMatcherLexer, $absolute, $routeName) { $routeName = $routeName ?: __METHOD__; $nonSiteAccessAwareRoutes = array('_dontwantsiteaccess'); $generator = $this->getMock('Symfony\\Component\\Routing\\Generator\\UrlGeneratorInterface'); $generator->expects($this->once())->method('generate')->with($routeName)->will($this->returnValue($urlGenerated)); /** @var DefaultRouter|\PHPUnit_Framework_MockObject_MockObject $router */ $router = $this->generateRouter(array('getGenerator')); $router->expects($this->any())->method('getGenerator')->will($this->returnValue($generator)); // If matcher is URILexer, we make it act as it's supposed to, prepending the siteaccess. if ($isMatcherLexer) { $matcher = $this->getMock('eZ\\Publish\\Core\\MVC\\Symfony\\SiteAccess\\URILexer'); // Route is siteaccess aware, we're expecting analyseLink() to be called if (!in_array($routeName, $nonSiteAccessAwareRoutes)) { $matcher->expects($this->once())->method('analyseLink')->with($relevantUri)->will($this->returnValue("/{$saName}{$relevantUri}")); } else { $matcher->expects($this->never())->method('analyseLink'); } } else { $matcher = $this->getMock('eZ\\Publish\\Core\\MVC\\Symfony\\SiteAccess\\Matcher'); } $sa = new SiteAccess($saName, 'test', $matcher); $router->setSiteAccess($sa); $requestContext = new RequestContext(); $urlComponents = parse_url($urlGenerated); if (isset($urlComponents['host'])) { $requestContext->setHost($urlComponents['host']); $requestContext->setScheme($urlComponents['scheme']); if (isset($urlComponents['port']) && $urlComponents['scheme'] === 'http') { $requestContext->setHttpPort($urlComponents['port']); } else { if (isset($urlComponents['port']) && $urlComponents['scheme'] === 'https') { $requestContext->setHttpsPort($urlComponents['port']); } } } $requestContext->setBaseUrl(substr($urlComponents['path'], 0, strpos($urlComponents['path'], $relevantUri))); $router->setContext($requestContext); $router->setNonSiteAccessAwareRoutes($nonSiteAccessAwareRoutes); $this->assertSame($expectedUrl, $router->generate($routeName, array(), $absolute)); }
/** * Forces the router to add the host if necessary. * * @param RequestContext $context * @param array $parameters * @param int $referenceType */ private function prepareDomain(RequestContext $context, array &$parameters, &$referenceType) { if (isset($parameters['_ssl'])) { $context->setScheme(true === $parameters['_ssl'] ? 'https' : 'http'); } if (isset($parameters['_domain']) && '' !== $parameters['_domain']) { $this->addHostToContext($context, $parameters, $referenceType); } unset($parameters['_domain'], $parameters['_ssl']); }
/** * Sets the context from the domain. * * @param RequestContext $context * @param array $parameters * @param string $referenceType */ private function setContextFromDomain(RequestContext $context, array &$parameters, &$referenceType) { list($host, $port) = explode(':', $parameters['_domain'], 2); if ($host === $context->getHost()) { return; } $isSsl = true === $parameters['_ssl']; $referenceType = UrlGeneratorInterface::ABSOLUTE_URL; $context->setHost($host); $context->setScheme($isSsl ? 'https' : 'http'); $context->setHttpPort($port ?: ($isSsl ? 443 : 80)); }