Unconditionally fetches a fresh response from the backend and
stores it in the cache if is cacheable.

@param Request $request A Request instance
@param bool    $catch   Whether to process exceptions

@return Response A Response instance
557186
protected function fetch(Request $request, $catch = false)
    {
        $subRequest = clone $request;

        // send no head requests because we want content
        if ('HEAD' === $request->getMethod()) {
            $subRequest->setMethod('GET');
        }

        // avoid that the backend sends no content
        $subRequest->headers->remove('if_modified_since');
        $subRequest->headers->remove('if_none_match');

        $response = $this->forward($subRequest, $catch);

        if ($response->isCacheable()) {
            $this->store($request, $response);
        }

        return $response;
    }
874128
protected function doRequest(Request $request)
    {

        $this->client->send($request, $response = new Response());

        return $response;
    }
449989
public function handleRequest(Request $request): Promise {
        $method = $request->getMethod();
        $path = \rawurldecode($request->getUri()->getPath());

        $toMatch = "{$method}\0{$path}";

        if (null === $match = $this->cache->get($toMatch)) {
            $match = $this->routeDispatcher->dispatch($method, $path);
            $this->cache->put($toMatch, $match);
        }

        switch ($match[0]) {
            case Dispatcher::FOUND:
                /**
                 * @var RequestHandler $requestHandler
                 * @var string[] $routeArgs
                 */
                list(, $requestHandler, $routeArgs) = $match;
                $request->setAttribute(self::class, $routeArgs);

                return $requestHandler->handleRequest($request);

            case Dispatcher::NOT_FOUND:
                if ($this->fallback !== null) {
                    return $this->fallback->handleRequest($request);
                }

                return $this->makeNotFoundResponse($request);

            case Dispatcher::METHOD_NOT_ALLOWED:
                return $this->makeMethodNotAllowedResponse($match[1], $request);

            default:
                // @codeCoverageIgnoreStart
                throw new \UnexpectedValueException(
                    "Encountered unexpected dispatcher code: " . $match[0]
                );
                // @codeCoverageIgnoreEnd
        }
    }
397894
public function calculate(Request $request) : Response
    {
        $url = $this->getVersionUrl($request->getVersion());

        try {
            $response = $this->getClient()->post(
                static::HOST . '/' . $url,
                array(
                    'body'    => json_encode($this->createRequestBody($request)),
                    'headers' => array(
                        'X-AuthToken'  => $this->key,
                        'Content-Type' => 'application/json'
                    )
                )
            );
        } catch (Exception $e) {
            throw new InvalidResponseException($e->getMessage(), $e->getCode(), $e);
        }

        $json = json_decode($response->getBody(), true);

        if (!is_array($json)) {
            throw new InvalidResponseException("Received invalid JSON.");
        }

        return new Response(
            $json['locationAuthHash'],
            $json['locationHash'],
            $json['requestHashes']
        );
    }
839069
public function store(Request $request)
    {
        $query = $this->getQuery();

        try {
            if ($request->input('query')) {
                $filter = new Filter($this->manager->newEntity()->getTable(), $this->queryable);
                $filter->build($query, $request->input('query'));
            }
        } catch (QuerySyntaxException $e) {
            return $this->error(['code' => 'QUERY_SYNTAX_ERROR', 'message' => 'Syntax error']);
        }

        $params = $request->only($this->fillable);

        DB::beginTransaction();

        $result = new Result();

        $query->chunk(100, function ($resources) use ($params, &$result) {
            foreach ($resources as $resource) {
                $result->addErrors($this->getManager()->update($resource, $params)->getErrors());
            }
        });

        if (!$result->ok()) {
            DB::rollBack();

            return $this->response(['errors' => $result->getSimpleErrors()], Response::HTTP_BAD_REQUEST);
        }

        DB::commit();

        return $this->response(null, Response::HTTP_OK);
    }
756657
private function createResponse(Request $request)
    {
        $response = new Response();
        $cacheLifetime = $request->attributes->get('_cacheLifetime');

        if ($cacheLifetime) {
            $response->setPublic();
            $response->headers->set(
                HttpCache::HEADER_REVERSE_PROXY_TTL,
                $cacheLifetime
            );
            $response->setMaxAge($this->getParameter('sulu_http_cache.handler.public.max_age'));
            $response->setSharedMaxAge($this->getParameter('sulu_http_cache.handler.public.shared_max_age'));
        }

        return $response;
    }
1210709
public function fetchResponse(Request $request, $waitForResult = true)
    {
        if ($request->hasResponse()) {
            return $request->getResponse();
        }

        $timer = $this->getFetchTimer($waitForResult);
        $req = new FetchRequest($request->getRequestId(), $waitForResult);

        do {
            try {
                $response = $this->sendFetchRequest($this->getManagerForRequest($request), $req);
                $result = $this->handleFetchResponse($response, $request);

                return $result;
            } catch (TimeoutException $ex) {
                $this->getLogger()->debug($request->getRequestId().': '.$ex->getMessage());
            }
        } while (!$timer->isExpired());

        throw new TimeoutException('Request '.$request->getRequestId().' timed out.');
    }
570520
public function swapAction(Request $request): Response
    {
        $form = $this->formFactory->swapLocation(
            new LocationSwapData()
        );
        $form->handleRequest($request);

        $location = $form->getData()->getCurrentLocation();

        if ($form->isSubmitted()) {
            $result = $this->submitHandler->handle($form, function (LocationSwapData $data) {
                $currentLocation = $data->getCurrentLocation();
                $newLocation = $data->getNewLocation();

                $childCount = $this->locationService->getLocationChildCount($currentLocation);
                $contentType = $newLocation->getContent()->getContentType();

                if (!$contentType->isContainer && $childCount) {
                    throw new \InvalidArgumentException(
                        'Cannot swap location that has sub items with a location that is not a container'
                    );
                }
                $this->locationService->swapLocation($currentLocation, $newLocation);

                $this->notificationHandler->success(
                    $this->translator->trans(
                        /** @Desc("Location '%name%' swaped with location '%location%'") */
                        'location.swap.success',
                        ['%name%' => $currentLocation->getContentInfo()->name, '%location%' => $newLocation->getContentInfo()->name],
                        'location'
                    )
                );

                return new RedirectResponse($this->generateUrl('_ezpublishLocation', [
                    'locationId' => $newLocation->id,
                    '_fragment' => LocationsTab::URI_FRAGMENT,
                ]));
            });

            if ($result instanceof Response) {
                return $result;
            }
        }

        return $this->redirect($this->generateUrl('_ezpublishLocation', [
            'locationId' => $location->id,
            '_fragment' => LocationsTab::URI_FRAGMENT,
        ]));
    }
231355
protected function doSendRequest(Request $request): Response
    {
        if (!$this->shouldUseGearman()) {
            return $this->locator->getRequestBus()->receiveRequest($request);
        }

        $envelope = new TransportEnvelope($request, 'php');
        $channel = $this->router->forRequest($request);

        try {
            $client = $this->getClient();
            $result = @$client->doNormal($channel, $envelope->toString(), (string)$request->get('request_id'));
            $this->validateReturnCode($client, $channel);
            return TransportEnvelope::fromString($result)->getMessage();
        } catch (\GearmanException $ge) {
            if (isset(self::$reconnectCodes[$ge->getCode()])) {
                $this->destroyClient();
                return $this->locator->getRequestBus()->receiveRequest($request);
            }

            throw $ge;
        } catch (\Throwable $e) {
            throw $e;
        }
    }
972104
public function render($request, Exception $exception)
    {
        $exception = $this->prepareException($exception);

        if ($exception instanceof HttpResponseException) {
            return $exception->getResponse();
        } elseif ($exception instanceof AuthenticationException) {
            return $this->unauthenticated($request, $exception);
        } elseif ($exception instanceof ValidationException) {
            return $this->convertValidationExceptionToResponse($exception, $request);
        } elseif ($this->isHttpException($exception) && $this->customErrorHtmlTemplateExists($exception)) {
            return $this->prepareResponse($request, $exception);
        }

        $flattened = FlattenException::create($exception);

        $code = $flattened->getStatusCode();
        $headers = $flattened->getHeaders();
        $response = $this->getContent($exception, $code, $request);

        // If it's already a response, return that.
        if (!$response instanceof BaseResponse) {
            $response = new Response($this->getContent($exception, $code, $request), $code, $headers);
        }

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

        $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 $e) {
            $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());

        foreach ($this->collectors as $collector) {
            $collector->collect($request, $response, $exception);

            // we need to clone for sub-requests
            $profile->addCollector(clone $collector);
        }

        return $profile;
    }
716594
public function collect(Request $request, Response $response, \Exception $exception = null)
    {
        $statData = $this->getStatsdDataFactory()->gauge($this->getStatsDataKey(), $this->getMemoryUsage());
        $this->addStatsData($statData);

        return true;
    }
1286806
public function handle(Request $request) : Response
	{
		if ($result = $this->handleContext($request, $this->rootContext)) {
			return $result;
		}
		
		if ($defaultHandler = $this->rootContext->getDefault()) {
			return $this->resultToResponse(
				call_user_func($defaultHandler, $request, null)
			);
		}
		
		throw new Exception('No matching route found. Set a default handler on root context to cover this case.');
	}
954915
public function send(Request $request)
    {
        $httpRequest = $this->createHttpRequest($request);
        $response    = new GetResponse();

        try {
            $httpResponse = $this->client->send($httpRequest);
            $code         = $httpResponse->getStatusCode();
        } catch (RequestException $e) {
            if ($e->getCode() == 404 && $request->notfoundOk) {
                return $response;
            }

            throw $e;
        }

        if ( ! isset($this->validResponseCodes[$code])) {
            throw RiakTransportException::unexpectedStatusCode($code);
        }

        $contentList = $this->getRiakContentList($httpResponse);
        $vClock      = $httpResponse->getHeader('X-Riak-Vclock');

        $response->vClock = $vClock;
        $response->contentList = $contentList;

        return $response;
    }
505038
public function invalidateCacheAction(Request $request)
    {
        $this->get('lexik_translation.translator')->removeLocalesCacheFiles($this->getManagedLocales());

        $message = $this->get('translator')->trans('translations.cache_removed', array(), 'LexikTranslationBundle');

        if ($request->isXmlHttpRequest()) {
            $this->checkCsrf();

            return new JsonResponse(array('message' => $message));
        }

        $this->get('session')->getFlashBag()->add('success', $message);

        return $this->redirect($this->generateUrl('lexik_translation_grid'));
    }
211661
public function handle(Request $request) : Response
    {
        try {
            return $this->handleRequest($request);
        } catch (HttpException $e) {
            return $this->handleHttpException($e, $request);
        } catch (\Throwable $e) {
            return $this->handleUncaughtException($e, $request);
        }
    }
152405
public function recoveryAction(Request $request)
    {
        $form = $this->createForm('CoreBundle\Form\RecoveryEmailType');
        $form->handleRequest($request);
        
        if ($form->isSubmitted() && $form->isValid()) {
            $data = $form->getNormData();
            if(isset($data['email'])){
                $em = $this->getDoctrine()->getManager();
                $user = $em->getRepository('CoreBundle:BaseActor')->findOneByEmail($data['email']);
                
                if ($request->isXmlHttpRequest()) {
                    $returnValues = new stdClass();
                    if ($user instanceof BaseActor) {
                        $this->get('core.mailer')->sendRecoveryPasswordMessage($user);
                        $returnValues->status = 'success';
                        $returnValues->message = $this->get('translator')->trans('recovery.email.success');
                    } else {
                        $returnValues->status = 'error';
                        $returnValues->message = $this->get('translator')->trans('recovery.email.error');
                    }
                    $response = new Response();
                    $response->setContent(json_encode(array(
                        'answer' => $returnValues
                    )));
                    $response->headers->set('Content-Type', 'application/json');
                    return $response;
                }else{
                    if ($user instanceof BaseActor) {
                        $this->get('core.mailer')->sendRecoveryPasswordMessage($user); 
                        $this->get('session')->getFlashBag()->add('success', 'recovery.email.success');
                    } else {
                        $this->get('session')->getFlashBag()->add('danger', 'recovery.email.error');
                    }
                }
            }
            
        }
        
        return array('form' => $form->createView());
    }