setResponse example

// Retry-After will be random within a range defined in jsonapi settings.     // The goals are to keep it short and to reduce the thundering herd problem.     $header_settings = $this->config->get('jsonapi.settings')->get('maintenance_header_retry_seconds');
    $retry_after_time = rand($header_settings['min']$header_settings['max']);
    $http_exception = new HttpException(503, $this->maintenanceMode->getSiteMaintenanceMessage());
    $document = new JsonApiDocumentTopLevel(new ErrorCollection([$http_exception])new NullIncludedData()new LinkCollection([]));
    $response = new ResourceResponse($document$http_exception->getStatusCode()[
      'Content-Type' => 'application/vnd.api+json',
      'Retry-After' => $retry_after_time,
    ]);
    // Calling RequestEvent::setResponse() also stops propagation of event.     $event->setResponse($response);
  }

}

    // If the owner of the directory we extracted is the same as the owner of     // our configuration directory (e.g. sites/default) where we're trying to     // install the code, there's no need to prompt for FTP/SSH credentials.     // Instead, we instantiate a Drupal\Core\FileTransfer\Local and invoke     // update_authorize_run_install() directly.     if (fileowner($project_real_location) == fileowner($this->sitePath) && !$test_authorize) {
      $this->moduleHandler->loadInclude('update', 'inc', 'update.authorize');
      $filetransfer = new Local($this->root, \Drupal::service('file_system'));
      $response = call_user_func_array('update_authorize_run_install', array_merge([$filetransfer]$arguments));
      if ($response instanceof Response) {
        $form_state->setResponse($response);
      }
    }

    // Otherwise, go through the regular workflow to prompt for FTP/SSH     // credentials and invoke update_authorize_run_install() indirectly with     // whatever FileTransfer object authorize.php creates for us.     else {
      // The page title must be passed here to ensure it is initially used when       // authorize.php loads for the first time with the FTP/SSH credentials       // form.       system_authorized_init('update_authorize_run_install', __DIR__ . '/../../update.authorize.inc', $arguments$this->t('Update manager'));
      
$form['submit'] = [
      '#type' => 'submit',
      '#value' => 'Submit',
    ];
    return $form;
  }

  /** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setResponse(new JsonResponse($form_state->getValues()));
  }

}

        $this->httpUtils = $httpUtils;
        $this->targetUrl = $targetUrl;
    }

    public function onLogout(LogoutEvent $event): void
    {
        if (null !== $event->getResponse()) {
            return;
        }

        $event->setResponse($this->httpUtils->createRedirectResponse($event->getRequest()$this->targetUrl));
    }

    public static function getSubscribedEvents(): array
    {
        return [
            LogoutEvent::class => ['onLogout', 64],
        ];
    }
}
/** * Do the conversion if applicable and update the response of the event. */
    public function onKernelView(ViewEvent $event): void
    {
        $controllerResult = $event->getControllerResult();

        if (!$controllerResult instanceof ResponseInterface) {
            return;
        }

        $event->setResponse($this->httpFoundationFactory->createResponse($controllerResult));
    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::VIEW => 'onKernelView',
        ];
    }
}
public function onKernelRequest(RequestEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $method = $event->getRequest()->getRealMethod();

        if ($method === 'OPTIONS') {
            $response = new Response();
            $event->setResponse($response);
        }
    }

    public function onKernelResponse(ResponseEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $corsHeaders = [
            'Content-Type',
            
if ($flood_control_triggered = $form_state->get('flood_control_triggered')) {
        if ($flood_control_triggered == 'user') {
          $message = $this->formatPlural($flood_config->get('user_limit'), 'There has been more than one failed login attempt for this account. It is temporarily blocked. Try again later or <a href=":url">request a new password</a>.', 'There have been more than @count failed login attempts for this account. It is temporarily blocked. Try again later or <a href=":url">request a new password</a>.', [':url' => Url::fromRoute('user.pass')->toString()]);
        }
        else {
          // We did not find a uid, so the limit is IP-based.           $message = $this->t('Too many failed login attempts from your IP address. This IP address is temporarily blocked. Try again later or <a href=":url">request a new password</a>.', [':url' => Url::fromRoute('user.pass')->toString()]);
        }
        $response = $this->bareHtmlPageRenderer->renderBarePage(['#markup' => $message]$this->t('Login failed'), 'maintenance_page');
        $response->setStatusCode(403);
        $form_state->setResponse($response);
      }
      else {
        // Use $form_state->getUserInput() in the error message to guarantee         // that we send exactly what the user typed in. The value from         // $form_state->getValue() may have been modified by validation         // handlers that ran earlier than this one.         $user_input = $form_state->getUserInput();
        $query = isset($user_input['name']) ? ['name' => $user_input['name']] : [];
        $form_state->setErrorByName('name', $this->t('Unrecognized username or password. <a href=":password">Forgot your password?</a>', [':password' => Url::fromRoute('user.pass', []['query' => $query])->toString()]));
        $accounts = $this->userStorage->loadByProperties(['name' => $form_state->getValue('name')]);
        if (!empty($accounts)) {
          
$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 [
      'url' => '',
    ];
$view = $element['#view'];
    }

    $element += $view->element;
    $view->element = &$element;
    // Mark the element as being prerendered, so other code like     // \Drupal\views\ViewExecutable::setCurrentPage knows that its no longer     // possible to manipulate the $element.     $view->element['#pre_rendered'] = TRUE;

    if (isset($element['#response'])) {
      $view->setResponse($element['#response']);
    }

    if ($view && $view->access($element['#display_id'])) {
      if (!empty($element['#embed'])) {
        $element['view_build'] = $view->preview($element['#display_id']$element['#arguments']);
      }
      else {
        // Add contextual links to the view. We need to attach them to the dummy         // $view_array variable, since contextual_preprocess() requires that they         // be attached to an array (not an object) in order to process them. For         // our purposes, it doesn't matter what we attach them to, since once they
if ($fast_paths && preg_match($fast_paths$request->getPathInfo())) {
        $fast_404_html = strtr($config->get('fast_404.html')['@path' => Html::escape($request->getUri())]);
        $response = new HtmlResponse($fast_404_html, Response::HTTP_NOT_FOUND);
        // Some routes such as system.files conditionally throw a         // NotFoundHttpException depending on URL parameters instead of just the         // route and route parameters, so add the URL cache context to account         // for this.         $cacheable_metadata = new CacheableMetadata();
        $cacheable_metadata->setCacheContexts(['url']);
        $cacheable_metadata->addCacheTags(['4xx-response']);
        $response->addCacheableDependency($cacheable_metadata);
        $event->setResponse($response);
      }
    }
  }

  /** * Invalidates 4xx-response cache tag if fast 404 config is changed. * * @param \Drupal\Core\Config\ConfigCrudEvent $event * The configuration event. */
  public function onConfigSave(ConfigCrudEvent $event): void {
    


    /** * Catch exceptions: true * Throwable type: RuntimeException * Listener: true. */
    public function testHandleWhenControllerThrowsAnExceptionAndCatchIsTrueWithAHandlingListener()
    {
        $dispatcher = new EventDispatcher();
        $dispatcher->addListener(KernelEvents::EXCEPTION, function D$event) {
            $event->setResponse(new Response($event->getThrowable()->getMessage()));
        });

        $kernel = $this->getHttpKernel($dispatcherstatic fn () => throw new \RuntimeException('foo'));
        $response = $kernel->handle(new Request(), HttpKernelInterface::MAIN_REQUEST, true);

        $this->assertEquals('500', $response->getStatusCode());
        $this->assertEquals('foo', $response->getContent());
    }

    /** * Catch exceptions: true * Throwable type: TypeError * Listener: true. */
'#default_value' => 'opt2',
    ];

    $form['submit'] = ['#type' => 'submit', '#value' => 'Submit'];
    return $form;
  }

  /** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setResponse(new JsonResponse($form_state->getValues()));
  }

}
// If the owner of the last directory we extracted is the same as the       // owner of our configuration directory (e.g. sites/default) where we're       // trying to install the code, there's no need to prompt for FTP/SSH       // credentials. Instead, we instantiate a Drupal\Core\FileTransfer\Local       // and invoke update_authorize_run_update() directly.       if (fileowner($project_real_location) == fileowner($this->sitePath)) {
        $this->moduleHandler->loadInclude('update', 'inc', 'update.authorize');
        $filetransfer = new Local($this->root, \Drupal::service('file_system'));
        $response = update_authorize_run_update($filetransfer$updates);
        if ($response instanceof Response) {
          $form_state->setResponse($response);
        }
      }
      // Otherwise, go through the regular workflow to prompt for FTP/SSH       // credentials and invoke update_authorize_run_update() indirectly with       // whatever FileTransfer object authorize.php creates for us.       else {
        // The page title must be passed here to ensure it is initially used         // when authorize.php loads for the first time with the FTP/SSH         // credentials form.         system_authorized_init('update_authorize_run_update', __DIR__ . '/../../update.authorize.inc', [$updates]$this->t('Update manager'));
        $form_state->setRedirectUrl(system_authorized_get_url());
      }
$prefix . '_d' => 'd',
      $prefix . '_c' => new TranslatableMarkup('main c'),
      $prefix . '_b' => new TranslatableMarkup('main b'),
      $prefix . '_a' => 'a',
    ];
  }

  /** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setResponse(new JsonResponse($form_state->getValues()));
  }

}
/** * Do the conversion if applicable and update the response of the event. */
    public function onKernelView(ViewEvent $event): void
    {
        $controllerResult = $event->getControllerResult();

        if (!$controllerResult instanceof ResponseInterface) {
            return;
        }

        $event->setResponse($this->httpFoundationFactory->createResponse($controllerResult));
    }

    /** * {@inheritdoc} */
    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::VIEW => 'onKernelView',
        ];
    }
}
Home | Imprint | This part of the site doesn't use cookies.