setStatusCode example



      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')]);
        

class UpdateTestController extends ControllerBase {

  /** * Displays an Error 503 (Service unavailable) page. * * @return \Symfony\Component\HttpFoundation\Response * Returns the response with a special header. */
  public function updateError() {
    $response = new Response();
    $response->setStatusCode(503);
    $response->headers->set('Status', '503 Service unavailable');

    return $response;
  }

  /** * Page callback: Prints mock XML for the Update Manager module. * * The specific XML file to print depends on two things: the project we're * trying to fetch data for, and the desired "availability scenario" for that * project which we're trying to test. Before attempting to fetch this data (by * checking for updates on the available updates report), callers need to define * the 'update_test_xml_map' variable as an array, keyed by project name, * indicating which availability scenario to use for that project. * * @param string $project_name * The project short name the update manager is trying to fetch data for (the * fetch URLs are of the form: [base_url]/[project_name]/[core_version]). * @param string $version * The version of Drupal core. * * @return \Symfony\Component\HttpFoundation\BinaryFileResponse|Response * A BinaryFileResponse object containing the content of the XML release file * for the specified project if one is available; a Response object with no * content otherwise. */
if (!$request->isXmlHttpRequest()) {
                    $header = $this->headerPageletLoader->load($request$context);
                    $footer = $this->footerPageletLoader->load($request$context);
                    $errorTemplate->setHeader($header);
                    $errorTemplate->setFooter($footer);
                }

                $response = $this->renderStorefront($errorTemplate->getTemplateName()['page' => $errorTemplate]);
            }

            if ($exception instanceof HttpException) {
                $response->setStatusCode($exception->getStatusCode());
            }
        } catch (\Exception $e) { // final Fallback             $response = $this->renderStorefront(
                '@Storefront/storefront/page/error/index.html.twig',
                ['exception' => $exception, 'followingException' => $e]
            );

            $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        // After this controllers content is rendered (even if the flashbag was not used e.g. on a 404 page),

    protected function handleRequest(?RouteCollectionInterface $routes, Cache $cacheConfig, bool $returnResponse = false)
    {
        $this->forceSecureAccess();

        if ($this->request instanceof IncomingRequest && strtolower($this->request->getMethod()) === 'cli') {
            return $this->response->setStatusCode(405)->setBody('Method Not Allowed');
        }

        Events::trigger('pre_system');

        // Check for a cached page. Execution will stop         // if the page has been cached.         if (($response = $this->displayCache($cacheConfig)) instanceof ResponseInterface) {
            return $response;
        }

        $routeFilter = $this->tryToRouteIt($routes);

        
$this->assertEquals('', $response->getContent());
        $this->assertEquals($length$response->headers->get('Content-Length'), 'Content-Length should be as if it was GET; see RFC2616 14.13');
    }

    public function testPrepareRemovesContentForInformationalResponse()
    {
        $response = new Response('foo');
        $request = Request::create('/');

        $response->setContent('content');
        $response->setStatusCode(101);
        $response->prepare($request);
        $this->assertEquals('', $response->getContent());
        $this->assertFalse($response->headers->has('Content-Type'));

        $response->setContent('content');
        $response->setStatusCode(304);
        $response->prepare($request);
        $this->assertEquals('', $response->getContent());
        $this->assertFalse($response->headers->has('Content-Type'));
        $this->assertFalse($response->headers->has('Content-Length'));
    }

    
switch ($method) {
            case 'refresh':
                $this->setHeader('Refresh', '0;url=' . $uri);
                break;

            default:
                $this->setHeader('Location', $uri);
                break;
        }

        $this->setStatusCode($code);

        return $this;
    }

    /** * Set a cookie * * Accepts an arbitrary number of binds (up to 7) or an associative * array in the first parameter containing all the values. * * @param array|Cookie|string $name Cookie name / array containing binds / Cookie object * @param string $value Cookie value * @param string $expire Cookie expiration time in seconds * @param string $domain Cookie domain (e.g.: '.yourdomain.com') * @param string $path Cookie path (default: '/') * @param string $prefix Cookie name prefix ('': the default prefix) * @param bool|null $secure Whether to only transfer cookies via SSL * @param bool|null $httponly Whether only make the cookie accessible via HTTP (no javascript) * @param string|null $samesite * * @return $this */
$this->listener = new CacheAttributeListener();
        $this->response = new Response();
        $this->cache = new Cache();
        $this->request = $this->createRequest($this->cache);
        $this->event = $this->createEventMock($this->request, $this->response);
    }

    public function testWontReassignResponseWhenResponseIsUnsuccessful()
    {
        $response = $this->event->getResponse();

        $this->response->setStatusCode(500);

        $this->listener->onKernelResponse($this->event);

        $this->assertSame($response$this->event->getResponse());
    }

    public function testWontReassignResponseWhenNoConfigurationIsPresent()
    {
        $response = $this->event->getResponse();

        $this->request->attributes->remove('_cache');

        

    public function collect(Request $request, Response $response, \Throwable $exception = null): ?Profile
    {
        if (false === $this->enabled) {
            return null;
        }

        $profile = new Profile(substr(hash('sha256', uniqid(mt_rand(), true)), 0, 6));
        $profile->setTime(time());
        $profile->setUrl($request->getUri());
        $profile->setMethod($request->getMethod());
        $profile->setStatusCode($response->getStatusCode());
        try {
            $profile->setIp($request->getClientIp());
        } catch (ConflictingHeadersException) {
            $profile->setIp('Unknown');
        }

        if ($prevToken = $response->headers->get('X-Debug-Token')) {
            $response->headers->set('X-Previous-Debug-Token', $prevToken);
        }

        $response->headers->set('X-Debug-Token', $profile->getToken());

        
throw $e;
        }

        $response = $event->getResponse();

        // the developer asked for a specific status code         if (!$event->isAllowingCustomResponseCode() && !$response->isClientError() && !$response->isServerError() && !$response->isRedirect()) {
            // ensure that we actually have an error response             if ($e instanceof HttpExceptionInterface) {
                // keep the HTTP status code and headers                 $response->setStatusCode($e->getStatusCode());
                $response->headers->add($e->getHeaders());
            } else {
                $response->setStatusCode(500);
            }
        }

        try {
            return $this->filterResponse($response$request$type);
        } catch (\Throwable $e) {
            if ($e instanceof \Error && !$this->handleAllThrowables) {
                throw $e;
            }
        $error['@backtrace'] = Error::formatBacktrace($backtrace);
        $message = new FormattableMarkup(Error::DEFAULT_ERROR_MESSAGE . ' <pre class="backtrace">@backtrace</pre>', $error);
      }
    }

    $content_type = $event->getRequest()->getRequestFormat() == 'html' ? 'text/html' : 'text/plain';
    $content = $this->t('The website encountered an unexpected error. Please try again later.');
    $content .= $message ? '<br><br>' . $message : '';
    $response = new Response($content, 500, ['Content-Type' => $content_type]);

    if ($exception instanceof HttpExceptionInterface) {
      $response->setStatusCode($exception->getStatusCode());
      $response->headers->add($exception->getHeaders());
    }
    else {
      $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR, '500 Service unavailable (with message)');
    }

    $event->setResponse($response);
  }

  /** * Handles all 4xx errors that aren't caught in other exception subscribers. * * For example, we catch 406s and 403s generated when handling unsupported * formats. * * @param \Symfony\Component\HttpKernel\Event\ExceptionEvent $event * The event to process. */
if ('' === $start) {
                        $start = $fileSize - $end;
                        $end = $fileSize - 1;
                    } else {
                        $start = (int) $start;
                    }

                    if ($start <= $end) {
                        $end = min($end$fileSize - 1);
                        if ($start < 0 || $start > $end) {
                            $this->setStatusCode(416);
                            $this->headers->set('Content-Range', sprintf('bytes */%s', $fileSize));
                        } elseif ($end - $start < $fileSize - 1) {
                            $this->maxlen = $end < $fileSize ? $end - $start + 1 : -1;
                            $this->offset = $start;

                            $this->setStatusCode(206);
                            $this->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $start$end$fileSize));
                            $this->headers->set('Content-Length', $end - $start + 1);
                        }
                    }
                }
            }
$request->setControllerName($type);
        $request->setParam('id', $id);
        $request->setParam('subId', $subId);
        $request->setParam('version', $version);

        $method = strtoupper($request->getParam('_method', $request->getMethod()));
        $action = 'invalid';

        if ($method === 'GET' && $id === false) {
            $action = 'index';
            $response->setStatusCode(SymfonyResponse::HTTP_OK);
        } elseif ($method === 'GET') {
            $action = 'get';
            $response->setStatusCode(SymfonyResponse::HTTP_OK);
        } elseif ($method === 'PUT' && $id === false) {
            $action = 'batch';
            $response->setStatusCode(SymfonyResponse::HTTP_OK);
        } elseif ($method === 'PUT') {
            $action = 'put';
        } elseif ($method === 'POST') {
            $action = 'post';
            // Set default http status code for successful request
$value = substr($header$pos + 1);

                $this->response->setHeader($title$value);
            } elseif (strpos($header, 'HTTP') === 0) {
                preg_match('#^HTTP\/([12](?:\.[01])?) (\d+) (.+)#', $header$matches);

                if (isset($matches[1])) {
                    $this->response->setProtocolVersion($matches[1]);
                }

                if (isset($matches[2])) {
                    $this->response->setStatusCode((int) $matches[2]$matches[3] ?? null);
                }
            }
        }
    }

    /** * Set CURL options * * @return array * * @throws InvalidArgumentException */

        $ssi = new Ssi();
        $cache = $this->getCache(Request::create('/')new Response('foo'));
        $this->assertEquals('foo', $ssi->handle($cache, '/', '/alt', true));
    }

    public function testHandleWhenResponseIsNot200()
    {
        $this->expectException(\RuntimeException::class);
        $ssi = new Ssi();
        $response = new Response('foo');
        $response->setStatusCode(404);
        $cache = $this->getCache(Request::create('/')$response);
        $ssi->handle($cache, '/', '/alt', false);
    }

    public function testHandleWhenResponseIsNot200AndErrorsAreIgnored()
    {
        $ssi = new Ssi();
        $response = new Response('foo');
        $response->setStatusCode(404);
        $cache = $this->getCache(Request::create('/')$response);
        $this->assertEquals('', $ssi->handle($cache, '/', '/alt', true));
    }
$this->record($request, 'stale-while-revalidate');

            return true;
        }

        // wait for the lock to be released         if ($this->waitForLock($request)) {
            // replace the current entry with the fresh one             $new = $this->lookup($request);
            $entry->headers = $new->headers;
            $entry->setContent($new->getContent());
            $entry->setStatusCode($new->getStatusCode());
            $entry->setProtocolVersion($new->getProtocolVersion());
            foreach ($new->headers->getCookies() as $cookie) {
                $entry->headers->setCookie($cookie);
            }
        } else {
            // backend is slow as hell, send a 503 response (to avoid the dog pile effect)             $entry->setStatusCode(503);
            $entry->setContent('503 Service Unavailable');
            $entry->headers->set('Retry-After', 10);
        }

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