RedirectResponse example

->method('createRequest')->with($this->request, '/login')
            ->willReturn($subRequest);

        $handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, $options$this->logger);
        $result = $handler->onAuthenticationFailure($this->request, $this->exception);

        $this->assertSame($this->response, $result);
    }

    public function testRedirect()
    {
        $response = new RedirectResponse('/login');
        $this->httpUtils->expects($this->once())
            ->method('createRedirectResponse')->with($this->request, '/login')
            ->willReturn($response);

        $handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, []$this->logger);
        $result = $handler->onAuthenticationFailure($this->request, $this->exception);

        $this->assertSame($response$result);
    }

    public function testExceptionIsPersistedInSession()
    {


  /** * Loads a page that does a redirect. * * Drupal uses Symfony's RedirectResponse for generating redirects. That class * uses a lower-case 'http-equiv="refresh"'. * * @see \Symfony\Component\HttpFoundation\RedirectResponse */
  public function metaRefresh() {
    return new RedirectResponse(Url::fromRoute('test_page_test.test_page', []['absolute' => TRUE])->toString(), 302);
  }

  /** * Returns a page render array with 2 elements with the same HTML IDs. * * @return array * A render array as expected by * \Drupal\Core\Render\RendererInterface::render(). */
  public function renderPageWithDuplicateIds() {
    return [
      

      $uri = 'base:' . $parts['path'];
      $options = [
        'query' => $parts['query'],
        'fragment' => $parts['fragment'],
        'absolute' => TRUE,
      ];
      // Treat this as if it's user input of a path relative to the site's       // base URL.       $url = $this->unroutedUrlAssembler->assemble($uri$options);
    }
    $response = new RedirectResponse($url);
    $listener = function D$event) use ($response) {
      $event->setResponse($response);
    };
    // Add the listener to the event dispatcher.     $this->dispatcher->addListener(KernelEvents::RESPONSE, $listener);
  }

  /** * {@inheritdoc} */
  public function defaultConfiguration() {
    
return $elements;
  }

  /** * Initialize authorize.php during testing. * * @see system_authorized_init() */
  public function authorizeInit($page_title) {
    $authorize_url = Url::fromUri('base:core/authorize.php', ['absolute' => TRUE])->toString();
    system_authorized_init('system_test_authorize_run', __DIR__ . '/../../system_test.module', []$page_title);
    return new RedirectResponse($authorize_url);
  }

  /** * Sets a header. */
  public function setHeader(Request $request) {
    $query = $request->query->all();
    $response = new CacheableResponse();
    $response->headers->set($query['name']$query['value']);
    $response->getCacheableMetadata()->addCacheContexts(['url.query_args:name', 'url.query_args:value']);
    $response->setContent($this->t('The following header was set: %name: %value', ['%name' => $query['name'], '%value' => $query['value']]));

    
try {
                $this->tokenStorage->setToken($this->attemptSwitchUser($request$username));
            } catch (AuthenticationException $e) {
                // Generate 403 in any conditions to prevent user enumeration vulnerabilities                 throw new AccessDeniedException('Switch User failed: '.$e->getMessage()$e);
            }
        }

        if (!$this->stateless) {
            $request->query->remove($this->usernameParameter);
            $request->server->set('QUERY_STRING', http_build_query($request->query->all(), '', '&'));
            $response = new RedirectResponse($this->urlGenerator && $this->targetRoute ? $this->urlGenerator->generate($this->targetRoute) : $request->getUri(), 302);

            $event->setResponse($response);
        }
    }

    /** * Attempts to switch to another user and returns the new token if successfully switched. * * @throws \LogicException * @throws AccessDeniedException */
    

    // 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(). */
  protected function DbatchGet() {
    return batch_get();
  }

}

  protected function redirect($route_name, array $route_parameters = [], array $options = []$status = 302) {
    $options['absolute'] = TRUE;
    return new RedirectResponse(Url::fromRoute($route_name$route_parameters$options)->toString()$status);
  }

  /** * Returns the service container. * * This method is marked private to prevent sub-classes from retrieving * services from the container through it. Instead, * \Drupal\Core\DependencyInjection\ContainerInjectionInterface should be used * for injecting services. * * @return \Symfony\Component\DependencyInjection\ContainerInterface * The service container. */

    public function createRedirectResponse(Request $request, string $path, int $status = 302): RedirectResponse
    {
        if (null !== $this->secureDomainRegexp && 'https' === $this->urlMatcher->getContext()->getScheme() && preg_match('#^https?:[/\\\\]{2,}+[^/]++#i', $path$host) && !preg_match(sprintf($this->secureDomainRegexp, preg_quote($request->getHttpHost()))$host[0])) {
            $path = '/';
        }
        if (null !== $this->domainRegexp && preg_match('#^https?:[/\\\\]{2,}+[^/]++#i', $path$host) && !preg_match(sprintf($this->domainRegexp, preg_quote($request->getHttpHost()))$host[0])) {
            $path = '/';
        }

        return new RedirectResponse($this->generateUri($request$path)$status);
    }

    /** * Creates a Request. * * @param string $path A path (an absolute path (/foo), an absolute URL (http://...), or a route name (foo)) */
    public function createRequest(Request $request, string $path): Request
    {
        $newRequest = Request::create($this->generateUri($request$path), 'get', []$request->cookies->all()[]$request->server->all());

        
/** * Enables a ConfigTest object. * * @param \Drupal\config_test\Entity\ConfigTest $config_test * The ConfigTest object to enable. * * @return \Symfony\Component\HttpFoundation\RedirectResponse * A redirect response to the config_test listing page. */
  public function enable(ConfigTest $config_test) {
    $config_test->enable()->save();
    return new RedirectResponse($config_test->toUrl('collection', ['absolute' => TRUE])->toString());
  }

  /** * Disables a ConfigTest object. * * @param \Drupal\config_test\Entity\ConfigTest $config_test * The ConfigTest object to disable. * * @return \Symfony\Component\HttpFoundation\RedirectResponse * A redirect response to the config_test listing page. */
  
new Url('test_route_b', ['key' => 'value']['absolute' => TRUE]), 'test-route/value'],
    ];
  }

  /** * Tests the redirectForm() method with a response object. * * @covers ::redirectForm */
  public function testRedirectWithResponseObject() {
    $form_submitter = $this->getFormSubmitter();
    $redirect = new RedirectResponse('/example');
    $form_state = $this->createMock('Drupal\Core\Form\FormStateInterface');
    $form_state->expects($this->once())
      ->method('getRedirect')
      ->willReturn($redirect);

    $result_redirect = $form_submitter->redirectForm($form_state);

    $this->assertSame($redirect$result_redirect);
  }

  /** * Tests the redirectForm() method when no redirect is expected. * * @covers ::redirectForm */

  protected function handleException(\Exception $e$request$type) {
    if ($this->shouldRedirectToInstaller($e$this->container ? $this->container->get('database') : NULL)) {
      return new RedirectResponse($request->getBasePath() . '/core/install.php', 302, ['Cache-Control' => 'no-cache']);
    }

    if ($e instanceof HttpExceptionInterface) {
      $response = new Response($e->getMessage()$e->getStatusCode());
      $response->headers->add($e->getHeaders());
      return $response;
    }

    throw $e;
  }

  

        $request->getSession()->invalidate();

        return new Response('<html><body>Session cleared.</body></html>');
    }

    public function setFlashAction(Request $request$message)
    {
        $session = $request->getSession();
        $session->getFlashBag()->set('notice', $message);

        return new RedirectResponse($this->container->get('router')->generate('session_showflash'));
    }

    public function showFlashAction(Request $request)
    {
        $session = $request->getSession();

        if ($session->getFlashBag()->has('notice')) {
            [$output] = $session->getFlashBag()->get('notice');
        } else {
            $output = 'No flash was set.';
        }

        
use Symfony\Component\HttpKernel\DataCollector\RouterDataCollector;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelInterface;

class RouterDataCollectorTest extends TestCase
{
    public function testRouteRedirectResponse()
    {
        $collector = new RouterDataCollector();

        $request = Request::create('http://test.com/foo?bar=baz');
        $response = new RedirectResponse('http://test.com/redirect');

        $event = $this->createControllerEvent($request);

        $collector->onKernelController($event);
        $collector->collect($request$response);

        $this->assertTrue($collector->getRedirect());
        $this->assertEquals('http://test.com/redirect', $collector->getTargetUrl());
        $this->assertEquals('n/a', $collector->getTargetRoute());
    }

    
/** * Provides test data for testing the getRedirect() method. * * @return array * Returns some test data. */
  public function providerTestGetRedirect() {
    $data = [];
    $data[] = [[], NULL];

    $redirect = new RedirectResponse('/example');
    $data[] = [['redirect' => $redirect]$redirect];

    $data[] = [['redirect' => new Url('test_route_b', ['key' => 'value'])]new Url('test_route_b', ['key' => 'value'])];

    $data[] = [['programmed' => TRUE], NULL];
    $data[] = [['rebuild' => TRUE], NULL];
    $data[] = [['no_redirect' => TRUE], NULL];

    return $data;
  }

  
// 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 {
    $events = [];

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