Generates a URL from the given parameters.
public function testAbsoluteSecureUrlWithNonStandardPort() { $this->routeCollection->add('test', new Route('/testing')); $this->generator->setContext(array('base_url' => '/app.php', 'method' => 'GET', 'host' => 'localhost', 'port' => 8080, 'is_secure' => true)); $url = $this->generator->generate('test', array(), true); $this->assertEquals('https://localhost:8080/app.php/testing', $url); }
protected function getRouteUrl($name) { if (!isset($this->urlGenerator)) { throw new \Exception("URLGenerator was not set"); } return $this->urlGenerator->generate($name); }
/** * @Route("/url/{route}", bind="url", values={"route"=null}) */ public function urlAction($route) { if (null === $route) { $route = 'hello_name'; } return $this->urlGenerator->generate($route, array('name' => 'urs'), UrlGeneratorInterface::ABSOLUTE_URL); }
/** * @param GetResponseForExceptionEvent $event */ public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if ($exception instanceof NotInstalledException) { $response = new RedirectResponse($this->urlGenerator->generate('simplr_install_welcome')); $event->setResponse($response); return; } }
public function generate($name, $parameters = [], $referenceType = self::ABSOLUTE_PATH) { if ($this->locale !== null && !isset($parameters[RouteAttribute::LOCALE])) { $parameters[RouteAttribute::LOCALE] = $this->locale; } return parent::generate($name, $parameters, $referenceType); }
/** * {@inheritdoc} */ public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH) { // determine the most suitable locale to use for route generation $currentLocale = $this->context->getParameter('_locale'); if (isset($parameters['_locale'])) { $locale = $parameters['_locale']; } else { if ($currentLocale) { $locale = $currentLocale; } else { $locale = 'en'; } } try { if (false !== ($pos = strpos($name, I18nControllerCollection::ROUTING_PREFIX))) { $name = substr($name, $pos + strlen(I18nControllerCollection::ROUTING_PREFIX)); } $url = parent::generate($locale . I18nControllerCollection::ROUTING_PREFIX . $name, $parameters, $referenceType); return $url; } catch (RouteNotFoundException $ex) { // fallback to default behavior } // use the default behavior if no localized route exists return parent::generate($name, $parameters, $referenceType); }
public function testListBucket() { $this->authorize(); $listUrl = $this->urlGenerator->generate('list', ['bucket' => 'foo']); $listBuckets = new Result(['Buckets' => [['Name' => 'foo', 'CreationDate' => '2014-08-01T14:00:00.000Z'], ['Name' => 'bar', 'CreationDate' => '2014-07-31T20:30:40.000Z']]]); $listObjects = new Result(['Contents' => [['Key' => 'baz', 'ETag' => '"' . md5('baz') . '"', 'LastModified' => '2014-09-10T11:12:13.000Z', 'Size' => 1024], ['Key' => 'qux', 'ETag' => '"' . md5('qux') . '"', 'LastModified' => '2014-09-11T21:22:23.000Z', 'Size' => 2048], ['Key' => 'quxx', 'ETag' => '"' . md5('quxx') . '"', 'LastModified' => '2014-09-12T00:00:00.000Z', 'Size' => 512]], 'IsTruncated' => false]); $this->s3ClientMock->expects($this->once())->method('listBuckets')->willReturn($listBuckets); $this->s3ClientMock->expects($this->once())->method('listObjects')->willReturn($listObjects); $crawler = $this->client->request('GET', $listUrl); $this->assertTrue($this->client->getResponse()->isOk()); // buckets $list = $crawler->filter('#list-bucket li'); $active = $list->filter('.active'); $this->assertCount(count($listBuckets['Buckets']), $list); $this->assertCount(1, $active); $this->assertEquals($list->eq(0), $active); $urlGenerator = $this->urlGenerator; $list->each(function (Crawler $bucket, $index) use($urlGenerator, $listBuckets) { $link = $bucket->filter('a'); $expectedName = $listBuckets['Buckets'][$index]['Name']; $this->assertEquals($expectedName, $link->text()); $this->assertEquals($urlGenerator->generate('list', ['bucket' => $expectedName]), $link->attr('href')); }); // objects $list = $crawler->filter('#list-object tbody tr'); $this->assertCount(count($listObjects['Contents']), $list); $list->each(function (Crawler $object, $index) use($listObjects) { $link = $object->filter('td')->eq(0)->filter('a'); $expectedKey = $listObjects['Contents'][$index]['Key']; $this->assertEquals($expectedKey, $link->text()); $this->assertEquals('http://foo.s3.amazonaws.com/' . $expectedKey, $link->attr('href')); $this->assertEquals($listObjects['Contents'][$index]['Size'], $object->filter('td')->eq(1)->text()); }); }
/** * @param $route_alias * @param $args * @return string */ public function url($route_alias, $args = array()) { $routes = $this->router->getRoutes(); $context = new RequestContext(self::getAssetDirectory()); $generator = new UrlGenerator($routes, $context); return $generator->generate($route_alias, $args); }
/** * {@inheritdoc} */ public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH) { $url = parent::generate($name, $parameters, $referenceType); if (substr($url, -6) == '/index') { $url = rtrim($url, "index"); } return $url; }
public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH) { try { return parent::generate($name, $parameters, $referenceType); } catch (RouteNotFoundException $e) { return $this->generator->generate($name, $parameters, $referenceType); } }
public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH) { if (null === $this->namespace || !$referenceType) { return parent::generate($name, $parameters, $referenceType); } else { return $this->getBaseUrl() . parent::generate($name, $parameters, false); } }
public function generate($name, array $parameters = array(), $absolute = false) { if (null === $this->namespace || !$absolute) { return parent::generate($name, $parameters, $absolute); } else { return $this->getBaseUrl() . parent::generate($name, $parameters, false); } }
/** * Get the URL to a named route. * * @param string $name * @param array $parameters * @param bool $absolute * @return string */ public function route($name, $parameters = array(), $absolute = true) { $route = $this->routes->get($name); if (isset($route) and $this->usingQuickParameters($parameters)) { $parameters = $this->buildParameterList($route, $parameters); } return $this->generator->generate($name, $parameters, $absolute); }
/** * @Route("/delete/{id}", bind="example_delete", asserts={"name"="\d+"}) * @param $id * @return RedirectResponse * @throws NotFoundHttpException */ public function deleteAction($id) { $example = $this->doctrine->getManager()->getRepository(get_class(new Example()))->find($id); if (is_null($example)) { throw new NotFoundHttpException("Can't find example with id {$id}"); } $this->doctrine->getManager()->remove($example); $this->doctrine->getManager()->flush(); return new RedirectResponse($this->urlGenerator->generate('example_list'), 302); }
public function path($routeName, $parameters = array()) { /** @var Route $route */ $route = $this->routes->get($routeName); if ($route) { $context = new RequestContext(); $generator = new UrlGenerator($this->routes, $context); return $generator->generate($routeName, $parameters); } return ''; }
public function loginAction(Request $req, Twig_Environment $twig, SecurityContext $sc, UrlGenerator $urlgen) { if ($sc->isGranted('IS_AUTHENTICATED_FULLY')) { return new RedirectResponse($urlgen->generate('home')); } else { $session = $req->getSession(); $errorConst = $sc::AUTHENTICATION_ERROR; $lastUsernameConst = $sc::LAST_USERNAME; return $twig->render('login.html.twig', array('error' => $session->has($errorConst) ? $session->get($errorConst)->getMessage() : null, 'last_username' => $session->get($lastUsernameConst))); } }
public static function generateURI($tag, $args = NULL) { $request = Request::createFromGlobals(); $locator = new FileLocator(array(__DIR__)); $loader = new YamlFileLoader($locator); $routes = $loader->load('../config/routes.yml'); $context = new RequestContext($request->getBaseUrl()); $generator = new UrlGenerator($routes, $context); $url = $generator->generate($tag); return $url; }
/** * @inheritdoc */ public function getRouteUrl($route, $parameters = null) { // Convert non-array parameters to empty array or single-value array with default parameter name. if (is_null($parameters)) { $parameters = array(); } elseif (!is_array($parameters)) { $parameters = array($this->getDefaultRouteParameterName() => $parameters); } // Generate the URL $configuredRoute = $this->config(sprintf('routes.%s', $route), $route); // TODO Allow configuration between absolute URL, absolute path, network URL, relative path, and path relative to base return $this->urlGenerator->generate($configuredRoute, $parameters, UrlGenerator::ABSOLUTE_URL); }
public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH) { // Check if this URL needs a CSRF token. if (null !== ($route = $this->routes->get($name))) { if ($csrfField = $route->getDefault(Route::CSRF_ATTRIBUTE_NAME)) { $parameters[$csrfField] = $route->getCsrfToken($name, $parameters, $this->_session->getId(), $this->_pepper); } } array_walk($parameters, function (&$item) { if ($item instanceof Slug) { $item = (string) $item; $item = $item === '/' ? $item : ltrim($item, '/'); } }); return parent::generate($name, $parameters, $referenceType); }
public function execute(InputInterface $input, OutputInterface $output) { $container = $this->getContainer(); $tubeManipulator = $container->get('velikan_tube_crawler.tube_manipulator'); $tubes = []; if ($tubeId = $input->hasArgument('tube-id')) { $tubes[] = $tubeManipulator->find($tubeId); } else { $tubes = $tubeManipulator->findAll(); } $uriFetchAdapter = $container->get('velikan_tube_crawler.uri_fetch_adapter'); $parsedVideoCounter = 0; $videoParser = $container->get('velikan_tube_crawler.video_parser'); /** @var Tube $tube */ $tube = null; $fetchAdapterFunction = function ($responseBody, $pageIndex) use(&$tube, $tubeManipulator, $videoParser, $output, &$parsedVideoCounter) { $videos = $videoParser->parse($responseBody, $tube->getVideoBlockSelector(), $tube->getVideoUriSelector(), $tube->getVideoImageSelector(), $tube->getVideoTitleSelector()); foreach ($videos as $parsedVideo) { $video = new Video(); $video->setTube($tube); $video->setVideoUri($parsedVideo['uri']); $video->setImageUri($parsedVideo['image']); $video->setTitle($parsedVideo['title']); $tubeManipulator->testAndCreateVideo($video); } $parsedVideoCounter += count($videos); $output->writeln(sprintf('Parsed %d videos for page %d (%d overall)', count($videos), $pageIndex, $parsedVideoCounter)); }; /** @var Tube $tube */ foreach ($tubes as $tube) { $output->writeln('Fetching videos for <info>' . $tube->getName() . '</info>'); $routeCollection = new RouteCollection(); $routeCollection->add('uri', new Route($tube->getUrn())); $requestContext = new RequestContext(Tube::$schemeList[$tube->getScheme()] . '://' . $tube->getHost()); $generator = new UrlGenerator($routeCollection, $requestContext); $startingPageNumber = $tube->getStartingPageNumber(); for ($i = $startingPageNumber; $i < $input->getOption('pages') + $startingPageNumber; $i++) { $uri = urldecode($generator->generate('uri', ['page' => $i])); $uriFetchAdapter->addUri($uri); } $uriFetchAdapter->fetch($fetchAdapterFunction, $tube->getCanFetchMultithreaded(), $tube->getThreadCount()); } }
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; }
/** * {@inheritdoc} */ public function generate($name, $parameters = [], $referenceType = self::ABSOLUTE_PATH) { // Determine the most suitable locale to use for route generation $currentLocale = $this->context->getParameter('_locale'); if (isset($parameters['_locale'])) { $locale = $parameters['_locale']; } elseif ($currentLocale) { $locale = $currentLocale; } else { $locale = $this->defaultLocale; } try { $i18nRouteName = sprintf('%s%s%s', $locale, I18nLoader::ROUTING_PREFIX, $name); $url = parent::generate($i18nRouteName, $parameters, $referenceType); return $url; } catch (RouteNotFoundException $e) { // Nothing to do } return parent::generate($name, $parameters, $referenceType); }
/** * {@inheritDoc} * @param $name string * @param $parameters array * @param $referenceType boolean|integer * @see \Symfony\Component\Routing\Generator\UrlGenerator::generate() */ public function generate($name, $parameters = array(), $referenceType = false) { //Since Symfony 3 dropped compatibility for booleans //and completely swapped the logic, let's provide our own compatibility layer. //We only want to touch booleans. Let proper integer-constant calls to go through. if ($referenceType === true) { $referenceType = UrlGeneratorInterface::ABSOLUTE_URL; } else { if ($referenceType === false) { $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH; } } $route = $this->routes->get($name); if ($route instanceof Route) { $isRouteLocaleAware = strpos($route->getPath(), '{locale}') !== false; if ($isRouteLocaleAware) { if (!array_key_exists('locale', $parameters)) { try { $parameters['locale'] = $this->getRequest()->getLocale(); } catch (\RuntimeException $e) { //Not running in a request context. } } } else { //Route that doesn't take a locale. If one was provided, get rid of it. //This is necessary, because we put certain systems into single-locale mode //(and transparently remove {locale} from routes. //Still, some code passes locales around.. But the routes no longer need it. //Instead of fixing all these passers so that they don't pass when in single-locale mode, //we do this transparently here. // //Caveat: If someone uses a non-locale-aware route, but wants a `locale` query string, //(`locale` meaning something possibly-unrelated to this library), //we would strip it as well and not pass it along. //This is a known problem. We take over `locale` and don't let people use it when they //include this library. unset($parameters['locale']); } } return parent::generate($name, $parameters, $referenceType); }
/** * @param string $name * @param array $parameters * @param int $referenceType * * @return string */ public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH) { if (isset($parameters[self::REDIRECT_TO_LANGUAGE])) { try { $name = $this->nodeManager->getNodeRouteName($name, $parameters[self::REDIRECT_TO_LANGUAGE]); } catch (NodeNotFoundException $e) { throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name)); } unset($parameters[self::REDIRECT_TO_LANGUAGE]); return parent::generate($name, $parameters, $referenceType); } $site = $this->siteRepository->findOneBySiteId($this->currentSiteManager->getCurrentSiteId()); if (null === $site) { throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name)); } $aliasId = $site->getMainAliasId(); $request = $this->requestStack->getMasterRequest(); if ($request) { $aliasId = $request->get('aliasId', $aliasId); } $uri = parent::generate($aliasId . '_' . $name, $parameters, $referenceType); return $uri; }
/** * Generate an url for a supplied route * * @param string $name The path * @param array $parameters The route parameters * @param bool $absolute Absolute url or not * * @return null|string */ public function generate($name, $parameters = array(), $absolute = UrlGeneratorInterface::ABSOLUTE_URL) { $this->urlGenerator = new UrlGenerator($this->routeCollection, $this->context); return $this->urlGenerator->generate($name, $parameters, $absolute); }
/** * {@inheritdoc} */ public function generate($name, $parameters = [], $referenceType = self::ABSOLUTE_PATH) { $generator = new UrlGenerator($this->getRouteCollection(), $this->getContext(), $this->logger); return $generator->generate($name, $parameters, $referenceType); }
/** * Generate an url for a supplied route * * @param string $name The path * @param array $parameters The route parameters * @param bool $absolute Absolute url or not * * @return null|string */ public function generate($name, $parameters = array(), $absolute = false) { $this->urlGenerator = new UrlGenerator($this->routeCollection, $this->context); return $this->urlGenerator->generate($name, $parameters, $absolute); }
/** * 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); $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') { 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); $url_generator = new UrlGenerator($this->route_collection, $context); $route_url = $url_generator->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); }
function freezeRoute($route, $parameters = array()) { if (in_array($route, $this->frozenRoutes)) { return; } $requestContext = new RequestContext(); $generator = new UrlGenerator($this->application['routes'], $requestContext); try { $url = $generator->generate($route, $parameters); } catch (\Exception $e) { } if (isset($url)) { $this->frozenRoutes[] = $route; return $this->freezeUrl($url); } }
/** * @param UrlGenerator $generator * @param string $api_name * @return string */ public static function generate_login_url(UrlGenerator $generator, $api_name) { return $generator->generate('prod_bridge_login', ['api_name' => strtolower($api_name)], UrlGenerator::ABSOLUTE_URL); }