Throw a too many redirects exception for a request

@param RequestInterface $original Request
@param int              $max      Max allowed redirects

@throws TooManyRedirectsException when too many redirects have been issued
484410
protected function throwTooManyRedirectsException(RequestInterface $original, $max)
    {
        $original->getEventDispatcher()->addListener(
            'request.complete',
            $func = function ($e) use (&$func, $original, $max) {
                $original->getEventDispatcher()->removeListener('request.complete', $func);
                $str = "{$max} redirects were issued for this request:\n" . $e['request']->getRawHeaders();
                throw new TooManyRedirectsException($str);
            }
        );
    }
6308
public function create(RedirectUriInterface $redirectUri): RedirectUriInterface
    {
        try {
            $now    = $this->ignoreException(function (): DateTimeImmutable {
                return new DateTimeImmutable();
            });
            $schema = $this->getDatabaseSchema();
            $this->createResource([
                $schema->getRedirectUrisClientIdentityColumn() => $redirectUri->getClientIdentifier(),
                $schema->getRedirectUrisValueColumn()          => $redirectUri->getValue(),
                $schema->getRedirectUrisCreatedAtColumn()      => $now,
            ]);
            $identifier = $this->getLastInsertId();

            $redirectUri->setIdentifier($identifier)->setCreatedAt($now);

            return $redirectUri;
        } catch (RepositoryException $exception) {
            $message = 'Client redirect URI creation failed.';
            throw new RepositoryException($message, 0, $exception);
        }
    }
1052188
public function canDisplay(Exception $original, Exception $transformed, int $code)
    {
        $redirect = $transformed instanceof HttpExceptionInterface && $transformed->getStatusCode() === 401;

        return $redirect && !$this->request->is('api*');
    }
358243
public function process(Request $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // Check if there is a limit of input number in php
        // Throw exception if the limit is reached
        if (ini_get('max_input_vars') || ini_get('suhosin.get.max_vars')) {
            $maxGet = $this->getMinInConfiguration(ini_get('max_input_vars'), ini_get('suhosin.get.max_vars'));
            if ($maxGet !== null) {
                $this->count = 0;
                array_walk_recursive($_GET, array($this, 'countRecursive'));
                if ($this->count === $maxGet) {
                    throw new SplashException('Max input vars reaches for get parameters ('.$maxGet.'). Check your variable max_input_vars in php.ini or suhosin module suhosin.get.max_vars.');
                }
            }
        }
        if (ini_get('max_input_vars') || ini_get('suhosin.post.max_vars')) {
            $maxPost = $this->getMinInConfiguration(ini_get('max_input_vars'), ini_get('suhosin.post.max_vars'));
            if ($maxPost !== null) {
                $this->count = 0;
                array_walk_recursive($_POST, array($this, 'countRecursive'));
                if ($this->count === $maxPost) {
                    throw new SplashException('Max input vars reaches for post parameters ('.$maxPost.'). Check your variable max_input_vars in php.ini or suhosin module suhosin.post.max_vars.');
                }
            }
        }
        if (ini_get('max_input_vars') || ini_get('suhosin.request.max_vars')) {
            $maxRequest = $this->getMinInConfiguration(ini_get('max_input_vars'), ini_get('suhosin.request.max_vars'));
            if ($maxRequest !== null) {
                $this->count = 0;
                array_walk_recursive($_REQUEST, array($this, 'countRecursive'));
                if ($this->count === $maxRequest) {
                    throw new SplashException('Max input vars reaches for request parameters ('.$maxRequest.'). Check your variable max_input_vars in php.ini or suhosin module suhosin.request.max_vars.');
                }
            }
        }
        if (isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post' && empty($_POST) && empty($_FILES)) {
            $maxPostSize = self::iniGetBytes('post_max_size');
            if ($_SERVER['CONTENT_LENGTH'] > $maxPostSize) {
                throw new SplashException(
                    sprintf('Max post size exceeded! Got %s bytes, but limit is %s bytes. Edit post_max_size setting in your php.ini.',
                        $_SERVER['CONTENT_LENGTH'],
                        $maxPostSize
                    )
                );
            }
        }

        //If no Exception has been thrown, call next router
        return $handler->handle($request);
    }
353467
public function redirectAction(Request $request, Error404 $error404)
    {
        $redirection = new ErrorRedirection();
        $redirection->setError($error404);

        $form = $this->getError404RedirectionForm($redirection);
        $form->handleRequest($request);

        if ($request->query->get('novalidate', false) === false) {
            if ($form->isValid()) {
                if ($redirection->getLink()->getLinkType() !== Link::TYPE_NONE) {
                    $error404->setRedirection($redirection);
                    $redirection->setError($error404);
                    $redirection->setUrl($error404->getUrl());

                    $em = $this->getDoctrine()->getManager();
                    $em->persist($redirection);
                    $em->flush();

                    $this->congrat($this->get('translator')->trans('victoire.404.redirection.success'));

                    return $this->returnAfterRemoval($error404);
                }

                $form->addError(new FormError($this->get('translator')->trans('victoire.404.form.error.blank')));
            }

            $this->warn($this->get('translator')->trans('victoire.404.form.error.unvalid'));

            return new Response($this->renderView('@VictoireSeo/Error404/_list.html.twig', [
                'form'     => $form->createView(),
                'error'    => $error404,
                'isOpened' => true,
            ]), 200, [
                'X-Inject-Alertify' => true,
            ]);
        }

        // rebuild form to avoid wrong form error
        $form = $this->getError404RedirectionForm($redirection);

        return new JsonResponse([
            'html' => $this->renderView('@VictoireSeo/Error404/_list.html.twig', [
                'form'     => $form->createView(),
                'error'    => $error404,
                'isOpened' => true,
            ]),
        ]);
    }
1360602
public function setRedirect($redirect)
    {
        /**
         * Changing the redirect also changes the secure[data] parameter. Since we
         * base our signature off of this it cannot be changed once the signature
         * has been generated.
         */
        if (isset($this->requestSignature)) {
            throw new BadMethodCallException('The signature for this request has already been generated.');
        }

        $this->redirect = $redirect;
        $this->mergeRedirect();
    }
505042
public function setRedirectLimit($limit)
    {
        if (!is_int($limit)) {
            throw new InvalidArgumentException('redirectLimit must be an integer.');
        }

        if ($limit < 1) {
            throw new InvalidArgumentException('redirectLimit must be greater than or equal to one.');
        }

        $this->redirectLimit = $limit;

        return $this;
    }
180879
public function followRedirect()
    {
        if (empty($this->redirect)) {
            throw new \LogicException('The request was not redirected.');
        }

        if (-1 !== $this->maxRedirects) {
            if ($this->redirectCount > $this->maxRedirects) {
                $this->redirectCount = 0;
                throw new \LogicException(sprintf('The maximum number (%d) of redirections was reached.', $this->maxRedirects));
            }
        }

        $request = $this->internalRequest;

        if (\in_array($this->internalResponse->getStatusCode(), [301, 302, 303])) {
            $method = 'GET';
            $files = [];
            $content = null;
        } else {
            $method = $request->getMethod();
            $files = $request->getFiles();
            $content = $request->getContent();
        }

        if ('GET' === strtoupper($method)) {
            // Don't forward parameters for GET request as it should reach the redirection URI
            $parameters = [];
        } else {
            $parameters = $request->getParameters();
        }

        $server = $request->getServer();
        $server = $this->updateServerFromUri($server, $this->redirect);

        $this->isMainRequest = false;

        $response = $this->request($method, $this->redirect, $parameters, $files, $server, $content);

        $this->isMainRequest = true;

        return $response;
    }
853623
private function withHeaders($request, $remaining, $retry = null)
  {
    $request->headers->addMany([
      'X-RateLimit-Limit' => $this->max,
      'X-RateLimit-Remaining' => ($remaining == 0 ? $remaining : $remaining - 1)
    ]);

    if ($retry !== null) {
      $request->headers->add('X-RateLimit-Reset', $retry);
    }
  }
632570
public function run(HTTPRequest $request) {
		$options = $request->getRoute()->getOptions();
		if( !empty($options['url_config']) ) {
			$url = AppConfig::instance()->get($options['url_config']);
			if( !$url ) {
				throw new Exception('The RedirectController requires a valid url_config option, please check your configuration.');
			}
		} else
		if( empty($options['redirect']) ) {
			throw new Exception('The RedirectController requires a redirect option, add it to your route configuration.');
		} else {
			$url = u($options['redirect']);
		}
		return new RedirectHTTPResponse($url);
	}
309903
protected function parseMaxAge(ServerRequestInterface $request) : int
    {
        $item = $this->settings['maxAge'];
        // we allow callables to be set (along with strings) so we can vary things upon requests.
        if (true === is_callable($item)) {
            // all callbacks are made with the request as the second parameter.
            $item = call_user_func($item, $request);
        }

        // maxAge needs to be an int - if it isn't, throw an exception.
        if (false === is_int($item)) {
            throw new \InvalidArgumentException('maxAge should be an int value');
        }

        // if it is less than zero, reject it as "faulty"
        if ($item < 0) {
            throw new \InvalidArgumentException('maxAge should be 0 or more');
        }

        // return our integer maximum age to cache.
        return $item;
    }
466392
public function retriesLeft($key, $maxAttempts)
    {
        $attempts = $this->attempts($key);

        return ($attempts === 0) ? $maxAttempts : $maxAttempts - $attempts + 1;
    }
109949
public static function fromRequest(RequestInterface $request, \Exception $previous): ParserException
    {
        $message = sprintf('Failed to parse \'%s\'', $request->getPath());

        return new self($message, $previous->getCode(), $previous);
    }
385962
private function validate(RedirectRouteInterface $entity)
    {
        if ('' === $entity->getTarget() && Response::HTTP_GONE !== (int)$entity->getStatusCode()) {
            throw new TargetIsEmptyException($entity);
        }

        if (in_array(strtolower($entity->getSource()), $this->sources)) {
            throw new DuplicatedSourceException($entity);
        }
    }
1141524
private function validateRedirections()
    {
        foreach ($this->redirections as $redirection)
        {
            if(!(
                array_key_exists('source', $redirection)
                &&
                array_key_exists('target', $redirection)
                &&
                array_key_exists('type', $redirection)
            ))
            {
                throw new ConfigurationException("Invalid redirection line: " . implode(',', $redirection) . ".");
            }
        }
    }
1157126
public void setMaxRetryTimeMillis(long maxRetryTimeMillis) {
        if (this.httpClient instanceof DefaultHttpClient) {
            ((DefaultHttpClient) this.httpClient).setMaxRetryTimeMillis(maxRetryTimeMillis);
        }
        else
            throw new UnsupportedOperationException("Invalid operation for class " + this.httpClient.getClass());
    }
1147378
public function redirect($to, $full = false)
    {
        $to = trim($to, '/');
        if (!$full && !Str::startsWith(App::$Alias->baseUrl, $to)) {
            $to = App::$Alias->baseUrl . '/' . $to;
        }
        $redirect = new FoundationRedirect($to);
        $redirect->send();
        exit('Redirecting to ' . $to . ' ...');
    }