fromUserInput example

$initials = [];
    foreach ($this->taxonomyTerms as $term) {
      $char = mb_strtolower(substr($term->label(), 0, 1));
      $initials += [$char => 0];
      $initials[$char]++;
    }

    $this->drupalGet('test_taxonomy_glossary');
    $assert_session = $this->assertSession();

    foreach ($initials as $char => $count) {
      $href = Url::fromUserInput('/test_taxonomy_glossary/' . $char)->toString();

      $xpath = $assert_session->buildXPathQuery('//a[@href=:href and normalize-space(text())=:label]', [
        ':href' => $href,
        ':label' => $char,
      ]);
      $link = $assert_session->elementExists('xpath', $xpath);

      // Assert that the expected number of results is indicated in the link.       preg_match("/{$char} \(([0-9]+)\)/", $link->getParent()->getText()$matches);
      $this->assertEquals($count$matches[1]);
    }

    
/** * Gets the form's redirect URL from 'destination' provide in the request. * * @return \Drupal\Core\Url|null * The redirect URL or NULL if dialog should just be closed. */
  protected function getRedirectUrl() {
    // \Drupal\Core\Routing\RedirectDestination::get() cannot be used directly     // because it will use <current> if 'destination' is not in the query     // string.     if ($this->getRequest()->query->has('destination') && $destination = $this->getRedirectDestination()->get()) {
      return Url::fromUserInput('/' . $destination);
    }
  }

}

  public function getRedirectPath() {
    return $this->redirect;
  }

  /** * {@inheritdoc} */
  public function getRedirectUrl() {
    if ($this->redirect) {
      $url = Url::fromUserInput($this->redirect);
    }
    else {
      $url = Url::fromRoute('<front>');
    }
    return $url;
  }

  /** * {@inheritdoc} */
  public function setRedirectPath($redirect) {
    
        elseif ($view->status() && $view->getExecutable()->displayHandlers->get($display['id'])->hasPath()) {
          $path = $view->getExecutable()->displayHandlers->get($display['id'])->getPath();

          if ($path && (!str_contains($path, '%'))) {
            // Wrap this in a try/catch as trying to generate links to some             // routes may throw a NotAcceptableHttpException if they do not             // respond to HTML, such as RESTExports.             try {
              if (!parse_url($path, PHP_URL_SCHEME)) {
                // @todo Views should expect and store a leading /. See:                 // https://www.drupal.org/node/2423913                 $url = Url::fromUserInput('/' . ltrim($path, '/'));
              }
              else {
                $url = Url::fromUri("base:$path");
              }
            }
            catch (NotAcceptableHttpException $e) {
              $url = '/' . $path;
            }

            $build['top']['actions']['path'] = [
              '#type' => 'link',
              
$menu_name$parent_link_path] = $value;

      // If the parent link path is external, URL will be useless because the       // link will definitely not correspond to a Drupal route.       if (UrlHelper::isExternal($parent_link_path)) {
        $links = $this->menuLinkStorage->loadByProperties([
          'menu_name' => $menu_name,
          'link.uri' => $parent_link_path,
        ]);
      }
      else {
        $url = Url::fromUserInput('/' . ltrim($parent_link_path, '/'));
        if ($url->isRouted()) {
          $links = $this->menuLinkManager->loadLinksByRoute($url->getRouteName()$url->getRouteParameters()$menu_name);
        }
      }
      if (!empty($links)) {
        return reset($links)->getPluginId();
      }
    }

    // Parent could not be determined.     throw new MigrateSkipRowException(sprintf("No parent link found for plid '%d' in menu '%s'.", $parent_id$value[0]));
  }
'route_parameters' => [],
      ];
      $next_destination = Url::fromRoute($next_destination['route_name']$next_destination['route_parameters']$next_destination['options']);
    }
    else {
      $options = UrlHelper::parse($next_destination);
      if ($destinations) {
        $options['query']['destinations'] = $destinations;
      }
      // Redirect to any given path within the same domain.       // @todo Revisit this in https://www.drupal.org/node/2418219.       $next_destination = Url::fromUserInput('/' . $options['path']$options);
    }
    return $next_destination;
  }

  /** * Gets the route parameter that should be used for Field UI routes. * * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type * The actual entity type, not the bundle (e.g. the content entity type). * @param string $bundle * The bundle name. * * @return array * An array that can be used a route parameter. */
        $options = [
          'attributes' => [
            'class' => [
              'views-more-link',
            ],
          ],
        ];
        if (UrlHelper::isExternal($more_link_path)) {
          $more_link_url = CoreUrl::fromUri($more_link_path$options);
        }
        else {
          $more_link_url = CoreUrl::fromUserInput('/' . $more_link_path$options);
        }
        $more_link = ' ' . $this->linkGenerator()->generate($more_link_text$more_link_url);
      }
    }

    if (!empty($alter['nl2br'])) {
      $value = nl2br($value);
    }

    if ($value_is_safe) {
      $value = ViewsRenderPipelineMarkup::create($value);
    }
return $header + parent::buildHeader();
  }

  /** * {@inheritdoc} */
  public function buildRow(EntityInterface $entity) {
    /** @var \Drupal\Core\Path\Entity\PathAlias $entity */
    $langcode = $entity->language()->getId();
    $alias = $entity->getAlias();
    $path = $entity->getPath();
    $url = Url::fromUserInput($path);

    $row['data']['alias']['data'] = [
      '#type' => 'link',
      '#title' => $alias,
      '#url' => $url,
    ];

    $row['data']['path']['data'] = [
      '#type' => 'link',
      '#title' => $path,
      '#url' => $url,
    ];
$assert_session->statusCodeEquals(200);
    $assert_session->pageTextContains($this->node1->getTitle());
    $assert_session->pageTextContains($this->node2->getTitle());

    // Test valid month value.     $this->drupalGet('test-month-date-plugin/10');
    $assert_session->statusCodeEquals(200);
    $assert_session->pageTextContains($this->node1->getTitle());
    $assert_session->pageTextNotContains($this->node2->getTitle());

    // Test query parameter.     $url = Url::fromUserInput('/test-month-date-plugin', [
      'query' => [
        'month' => 10,
      ],
    ]);
    $this->drupalGet($url);
    $assert_session->statusCodeEquals(200);
    $assert_session->pageTextContains($this->node1->getTitle());
    $assert_session->pageTextNotContains($this->node2->getTitle());

    // Test invalid month name.     $this->drupalGet('test-month-date-plugin/invalid-month');
    
protected static $modules = ['common_test', 'url_alter_test'];

  /** * Confirms that invalid URLs are filtered in link generating functions. */
  public function testLinkXSS() {
    // Test link generator.     $text = $this->randomMachineName();
    $path = "<SCRIPT>alert('XSS')</SCRIPT>";
    $encoded_path = "3CSCRIPT%3Ealert%28%27XSS%27%29%3C/SCRIPT%3E";

    $link = Link::fromTextAndUrl($text, Url::fromUserInput('/' . $path))->toString();
    $this->assertStringContainsString($encoded_path$linknew FormattableMarkup('XSS attack @path was filtered by \Drupal\Core\Utility\LinkGeneratorInterface::generate().', ['@path' => $path]));
    $this->assertStringNotContainsString($path$linknew FormattableMarkup('XSS attack @path was filtered by \Drupal\Core\Utility\LinkGeneratorInterface::generate().', ['@path' => $path]));

    // Test \Drupal\Core\Url.     $link = Url::fromUri('base:' . $path)->toString();
    $this->assertStringContainsString($encoded_path$linknew FormattableMarkup('XSS attack @path was filtered by #theme', ['@path' => $path]));
    $this->assertStringNotContainsString($path$linknew FormattableMarkup('XSS attack @path was filtered by #theme', ['@path' => $path]));
  }

  /** * Tests that #type=link bubbles outbound route/path processors' metadata. */
'#value' => $this->t('Apply'),
      '#id' => Html::getUniqueId('edit-submit-' . $view->storage->id()),
    ];

    if (!$view->hasUrl()) {
      // On any non views.ajax route, use the current route for the form action.       if ($this->getRouteMatch()->getRouteName() !== 'views.ajax') {
        $form_action = Url::fromRoute('<current>')->toString();
      }
      else {
        // On the views.ajax route, set the action to the page we were on.         $form_action = Url::fromUserInput($this->currentPathStack->getPath())->toString();
      }
    }
    else {
      $form_action = $view->getUrl()->toString();
    }

    $form['#action'] = $form_action;
    $form['#theme'] = $view->buildThemeFunctions('views_exposed_form');
    $form['#id'] = Html::cleanCssIdentifier('views_exposed_form-' . $view->storage->id() . '-' . $display['id']);
    // Labels are built too late for inline form errors to work, resulting     // in duplicated messages.
$this->assertSubString($result$expected_result);

      $expected_result = Url::fromRoute('entity.node.canonical', ['node' => '123']['query' => ['foo' => 'bar', 'bar' => 'baz'], 'absolute' => $absolute])->toString();
      $alter['path'] = 'node/123?foo=bar&bar=baz';
      $result = $renderer->executeInRenderContext(new RenderContext()function D) use ($id_field$row) {
        return $id_field->theme($row);
      });
      $this->assertSubString(Html::decodeEntities($result), Html::decodeEntities($expected_result));

      // @todo The route-based URL generator strips out NULL attributes.       // $expected_result = Url::fromRoute('entity.node.canonical', ['node' => '123'], ['query' => ['foo' => NULL], 'fragment' => 'bar', 'absolute' => $absolute])->toString();       $expected_result = Url::fromUserInput('/node/123', ['query' => ['foo' => NULL], 'fragment' => 'bar', 'absolute' => $absolute])->toString();
      $alter['path'] = 'node/123?foo#bar';
      $result = $renderer->executeInRenderContext(new RenderContext()function D) use ($id_field$row) {
        return $id_field->theme($row);
      });
      $this->assertSubString(Html::decodeEntities($result), Html::decodeEntities($expected_result));

      $expected_result = Url::fromRoute('<front>', []['absolute' => $absolute])->toString();
      $alter['path'] = '<front>';
      $result = $renderer->executeInRenderContext(new RenderContext()function D) use ($id_field$row) {
        return $id_field->theme($row);
      });
      
return $form;
  }

  /** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    if (!$form_state->isValueEmpty('redirection')) {
      if (!$form_state->isValueEmpty('destination')) {
        // The destination is a random URL, so we can't use routed URLs.         // @todo Revisit this in https://www.drupal.org/node/2418219.         $form_state->setRedirectUrl(Url::fromUserInput('/' . $form_state->getValue('destination')));
      }
    }
    else {
      $form_state->disableRedirect();
    }
  }

}
/** * Makes a subrequest to retrieve the custom error page. * * @param \Symfony\Component\HttpKernel\Event\ExceptionEvent $event * The event to process. * @param string $custom_path * The custom path to which to make a subrequest for this error message. * @param int $status_code * The status code for the error being handled. */
  protected function makeSubrequestToCustomPath(ExceptionEvent $event$custom_path$status_code) {
    $url = Url::fromUserInput($custom_path);
    if ($url->isRouted()) {
      $access_result = $this->accessManager->checkNamedRoute($url->getRouteName()$url->getRouteParameters(), NULL, TRUE);
      $request = $event->getRequest();

      // Merge the custom path's route's access result's cacheability metadata       // with the existing one (from the master request), otherwise create it.       if (!$request->attributes->has(AccessAwareRouterInterface::ACCESS_RESULT)) {
        $request->attributes->set(AccessAwareRouterInterface::ACCESS_RESULT, $access_result);
      }
      else {
        $existing_access_result = $request->attributes->get(AccessAwareRouterInterface::ACCESS_RESULT);
        
parent::buildOptionsForm($form$form_state);
  }

  /** * {@inheritdoc} */
  public function render(ResultRow $values) {
    $value = $this->getValue($values);
    if (!empty($this->options['display_as_link'])) {
      // @todo Views should expect and store a leading /. See:       // https://www.drupal.org/node/2423913       return Link::fromTextAndUrl($this->sanitizeValue($value), CoreUrl::fromUserInput('/' . $value))->toString();
    }
    else {
      return $this->sanitizeValue($value, 'url');
    }
  }

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