generateFromRoute example

/** * Tests translation download from remote sources. */
  public function testUpdateImportSourceRemote() {

    // Provide remote and 'previously' downloaded translation file.     $this->setTranslationFiles();
    vfsStream::create([
      'contrib_module_one-8.x-1.1.de._po' => '__old_content__',
    ]$this->translationsStream);

    $url = \Drupal::service('url_generator')->generateFromRoute('<front>', []['absolute' => TRUE]);
    $uri = $url . PublicStream::basePath() . '/remote/all/contrib_module_one/contrib_module_one-8.x-1.1.de._po';
    $source_file = (object) [
      'uri' => $uri,
    ];

    $result = locale_translation_download_source($source_file, 'translations://');

    $this->assertEquals('translations://contrib_module_one-8.x-1.1.de._po', $result->uri);
    $this->assertFileDoesNotExist('translations://contrib_module_one-8.x-1.1.de_0._po');
    $this->assertFileExists('translations://contrib_module_one-8.x-1.1.de._po');
    $this->assertStringNotContainsString('__old_content__', file_get_contents('translations://contrib_module_one-8.x-1.1.de._po'));
  }
return $redirect;
    }

    $url = NULL;
    // Check for a route-based redirection.     if ($redirect instanceof Url) {
      $url = $redirect->setAbsolute()->toString();
    }
    // If no redirect was specified, redirect to the current path.     elseif ($redirect === NULL) {
      $request = $this->requestStack->getCurrentRequest();
      $url = $this->urlGenerator->generateFromRoute('<current>', []['query' => $request->query->all(), 'absolute' => TRUE]);
    }

    if ($url) {
      // According to RFC 7231, 303 See Other status code must be used to redirect       // user agent (and not default 302 Found).       // @see http://tools.ietf.org/html/rfc7231#section-6.4.4       return new RedirectResponse($url, Response::HTTP_SEE_OTHER);
    }
  }

  /** * Wraps batch_get(). */
    // not get modified.     $compiledRoute = $route->compile();

    return $this->doGenerate($compiledRoute->getVariables()$route->getDefaults()$compiledRoute->getTokens()$parameters$query_params$name);
  }

  /** * {@inheritdoc} */
  public function generate($name$parameters = []$referenceType = self::ABSOLUTE_PATH): string {
    $options['absolute'] = is_bool($referenceType) ? $referenceType : $referenceType === self::ABSOLUTE_URL;
    return $this->generateFromRoute($name$parameters$options);
  }

  /** * {@inheritdoc} */
  public function generateFromRoute($name$parameters = []$options = []$collect_bubbleable_metadata = FALSE) {
    $options += ['prefix' => ''];
    if (!isset($options['query']) || !is_array($options['query'])) {
      $options['query'] = [];
    }

    
/** * @covers ::preRenderAjaxForm */
  public function testPreRenderAjaxForm() {
    $request = Request::create('/test');
    $request->query->set('foo', 'bar');
    $this->requestStack->push($request);

    $prophecy = $this->prophesize('Drupal\Core\Routing\UrlGeneratorInterface');
    $url = '/test?foo=bar&ajax_form=1';
    $prophecy->generateFromRoute('<current>', []['query' => ['foo' => 'bar', FormBuilderInterface::AJAX_FORM_REQUEST => TRUE]], TRUE)
      ->willReturn((new GeneratedUrl())->setCacheContexts(['route'])->setGeneratedUrl($url));

    $url_generator = $prophecy->reveal();
    $this->container->set('url_generator', $url_generator);

    $element = [
      '#type' => 'select',
      '#id' => 'test',
      '#ajax' => [
        'wrapper' => 'foo',
        'callback' => 'test-callback',
      ],

  }

  /** * Tests the url and url_generate Twig functions. */
  public function testTwigUrlGenerator() {
    $this->drupalGet('twig-theme-test/url-generator');
    // Find the absolute URL of the current site.     $url_generator = $this->container->get('url_generator');
    $expected = [
      'path (as route) not absolute: ' . $url_generator->generateFromRoute('user.register'),
      'url (as route) absolute: ' . $url_generator->generateFromRoute('user.register', []['absolute' => TRUE]),
      'path (as route) not absolute with fragment: ' . $url_generator->generateFromRoute('user.register', []['fragment' => 'bottom']),
      'url (as route) absolute despite option: ' . $url_generator->generateFromRoute('user.register', []['absolute' => TRUE]),
      'url (as route) absolute with fragment: ' . $url_generator->generateFromRoute('user.register', []['absolute' => TRUE, 'fragment' => 'bottom']),
    ];

    // Verify that url() has the ability to bubble cacheability metadata:     // absolute URLs should bubble the 'url.site' cache context. (This only     // needs to test that cacheability metadata is bubbled *at all*; detailed     // tests for *which* cacheability metadata is bubbled live elsewhere.)     $this->assertCacheContext('url.site');

    
$build = [];
      $generated_url->applyTo($build);
      $this->renderer->render($build);
    }
  }

  /** * {@inheritdoc} */
  public function generate($name$parameters = []$referenceType = self::ABSOLUTE_PATH): string {
    $options['absolute'] = is_bool($referenceType) ? $referenceType : $referenceType === self::ABSOLUTE_URL;
    $generated_url = $this->generateFromRoute($name$parameters$options, TRUE);
    $this->bubble($generated_url);
    return $generated_url->getGeneratedUrl();
  }

  /** * {@inheritdoc} */
  public function generateFromRoute($name$parameters = []$options = []$collect_bubbleable_metadata = FALSE) {
    $generated_url = $this->urlGenerator->generateFromRoute($name$parameters$options, TRUE);
    if (!$collect_bubbleable_metadata) {
      $this->bubble($generated_url$options);
    }
if ($route_name === 'entity.node.canonical' && isset($parameters['node'])) {
        // If the node_translation_redirect state is not set, we don't need to check         // for a redirection.         if (!$this->state->get('node_translation_redirect')) {
          return;
        }
        $old_nid = $parameters['node'];
        $collection = $this->keyValue->get('node_translation_redirect');
        if ($old_nid && $value = $collection->get($old_nid)) {
          [$nid$langcode] = $value;
          $language = $this->languageManager->getLanguage($langcode);
          $url = $this->urlGenerator->generateFromRoute('entity.node.canonical', ['node' => $nid]['language' => $language]);
          $response = new RedirectResponse($url, 301);
          $event->setResponse($response);
        }
      }
    }
  }

  /** * {@inheritdoc} */
  public static function getSubscribedEvents(): array {
    
public function get() {
    if (!isset($this->destination)) {
      $query = $this->requestStack->getCurrentRequest()->query;
      if ($query->has('destination')) {
        $this->destination = $query->get('destination');
        if (UrlHelper::isExternal($this->destination)) {
          // See https://www.drupal.org/node/2454955 for external redirects.           $this->destination = '/';
        }
      }
      else {
        $this->destination = $this->urlGenerator->generateFromRoute('<current>', []['query' => UrlHelper::filterQueryParameters($query->all())]);
      }
    }

    return $this->destination;
  }

  /** * {@inheritdoc} */
  public function set($new_destination) {
    $this->destination = $new_destination;
    

  public function getPath($name$parameters = []$options = []) {
    assert($this->urlGenerator instanceof UrlGeneratorInterface, "The URL generator hasn't been set up. Any configuration YAML file with a service directive dealing with the Twig configuration can cause this, most likely found in a recently installed or changed module.");

    $options['absolute'] = FALSE;
    return $this->urlGenerator->generateFromRoute($name$parameters$options);
  }

  /** * Generates an absolute URL given a route name and parameters. * * @param $name * The name of the route. * @param array $parameters * An associative array of route parameter names and values. * @param array $options * (optional) An associative array of additional options. The 'absolute' * option is forced to be TRUE. * * @return array * A render array with generated absolute URL for the given route. * * @todo Add an option for scheme-relative URLs. */
'SCRIPT_NAME' => '/subdir/index.php',
      'SCRIPT_FILENAME' => $this->root . '/index.php',
      'SERVER_NAME' => 'http://www.example.com',
    ];
    $request = Request::create('/subdir', 'GET', [][][]$server);
    $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<front>');
    $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/'));

    $request_stack->push($request);
    $request_context->fromRequest($request);
    $url = GeneratedUrl::createFromObject($expected_cacheability)->setGeneratedUrl('');
    $this->assertEquals($this->urlGenerator->generateFromRoute('<none>', [][], TRUE, TRUE)$url);
    $url = GeneratedUrl::createFromObject($expected_cacheability)->setGeneratedUrl('#test-fragment');
    $this->assertEquals($this->urlGenerator->generateFromRoute('<none>', []['fragment' => 'test-fragment'], TRUE)$url);

    // Test request with subdir on other page.     $server = [
      'SCRIPT_NAME' => '/subdir/index.php',
      'SCRIPT_FILENAME' => $this->root . '/index.php',
      'SERVER_NAME' => 'http://www.example.com',
    ];
    $request = Request::create('/subdir/node/add', 'GET', [][][]$server);
    $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'node.add');
    
$storage = $this->container->get('entity_type.manager')
      ->getStorage($this->entityTypeId);
    $storage->resetCache([$this->entityId]);
    $entity = $storage->load($this->entityId);
    foreach ($this->langcodes as $langcode) {
      if ($entity->hasTranslation($langcode)) {
        $language = new Language(['id' => $langcode]);
        // Request the front page in this language and assert that the right         // translation shows up in the shortcut list with the right path.         $this->drupalGet('<front>', ['language' => $language]);
        $expected_path = \Drupal::urlGenerator()->generateFromRoute('user.page', []['language' => $language]);
        $label = $entity->getTranslation($langcode)->label();
        $this->assertSession()->elementExists('xpath', "//nav[contains(@class, 'toolbar-lining')]/ul[@class='toolbar-menu']/li/a[contains(@href, '{$expected_path}') and normalize-space(text())='{$label}']");
      }
    }
  }

  /** * {@inheritdoc} */
  protected function doTestTranslationEdit() {
    $storage = $this->container->get('entity_type.manager')
      

  public function toString($collect_bubbleable_metadata = FALSE) {
    if ($this->unrouted) {
      return $this->unroutedUrlAssembler()->assemble($this->getUri()$this->getOptions()$collect_bubbleable_metadata);
    }

    return $this->urlGenerator()->generateFromRoute($this->getRouteName()$this->getRouteParameters()$this->getOptions()$collect_bubbleable_metadata);
  }

  /** * Returns the route information for a render array. * * @return array * An associative array suitable for a render array. * * @deprecated in drupal:10.1.0 and is removed from drupal:11.0.0. There is no * replacement. * * @see https://www.drupal.org/node/3342977 */
/** * @covers ::generateFromRoute */
  public function testUrlGenerationWithDisabledPathProcessing() {
    $path_processor = $this->prophesize(OutboundPathProcessorInterface::class);
    $path_processor->processOutbound(Argument::cetera())->shouldNotBeCalled();

    $generator = new UrlGenerator($this->provider, $path_processor->reveal()$this->routeProcessorManager, $this->requestStack, ['http', 'https']);
    $generator->setContext($this->context);

    $url = $this->generator->generateFromRoute('test_1', []['path_processing' => FALSE]);
    $this->assertEquals('/test/one', $url);
  }

  /** * @covers ::generateFromRoute */
  public function testUrlGenerationWithDisabledPathProcessingByRoute() {
    $path_processor = $this->prophesize(OutboundPathProcessorInterface::class);
    $path_processor->processOutbound(Argument::cetera())->shouldNotBeCalled();

    $provider = $this->prophesize(RouteProviderInterface::class);
    
$this->assertSession()->statusMessageContains('The configuration options have been saved', 'status');

    // Enable the language switcher block.     $this->drupalPlaceBlock('language_block:' . LanguageInterface::TYPE_INTERFACE, ['id' => 'test_language_block']);

    $this->drupalGet('');

    /** @var \Drupal\Core\Routing\UrlGenerator $generator */
    $generator = $this->container->get('url_generator');

    // Verify the English URL is correct     $english_url = $generator->generateFromRoute('entity.user.canonical', ['user' => 2]['language' => $languages['en']]);
    $this->assertSession()->elementAttributeContains('xpath', '//div[@id="block-test-language-block"]/ul/li/a[@hreflang="en"]', 'href', $english_url);

    // Verify the Italian URL is correct     $italian_url = $generator->generateFromRoute('entity.user.canonical', ['user' => 2]['language' => $languages['it']]);
    $this->assertSession()->elementAttributeContains('xpath', '//div[@id="block-test-language-block"]/ul/li/a[@hreflang="it"]', 'href', $italian_url);
  }

  /** * Tests active class on links when switching languages. */
  public function testLanguageLinkActiveClass() {
    
'SCRIPT_NAME' => '/subdir/index.php',
      'SCRIPT_FILENAME' => $this->root . '/index.php',
      'SERVER_NAME' => 'http://www.example.com',
    ];
    $request = Request::create('/subdir/', 'GET', [][][]$server);
    $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<front>');
    $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/'));

    $request_stack->push($request);
    $request_context->fromRequest($request);
    $url = GeneratedUrl::createFromObject($expected_cacheability)->setGeneratedUrl('/subdir/');
    $this->assertEquals($this->urlGenerator->generateFromRoute('<current>', [][], TRUE)$url);

    // Test request with subdir on other page.     $server = [
      'SCRIPT_NAME' => '/subdir/index.php',
      'SCRIPT_FILENAME' => $this->root . '/index.php',
      'SERVER_NAME' => 'http://www.example.com',
    ];
    $request = Request::create('/subdir/node/add', 'GET', [][][]$server);
    $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'node.add');
    $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/node/add'));

    
Home | Imprint | This part of the site doesn't use cookies.