Accept request, add auth headers and dispatch, then respond to any errors.

@param  \PeterColes\Betfair\Http\Client $request
@return Mixed
@throws Exception
14609
public function execute($request)
    {
        $result = $request->authHeaders()->send();

        if ($result->status === self::API_STATUS_FAIL) {
            throw new Exception('Error: '.$result->error);
        }

        return $result;
    }
1350994
public function handle(\Exception $ex, Request $request)
    {
        foreach ($this->callbacks as $exClass => $callback) {
            if ($ex instanceof $exClass) {
                $invoker = new Invoker();
                return $invoker->invoke($callback, [], [$ex, $request]);
            }
        }
    }
1072497
protected function dispatchRequest(Request $request): Collection
    {
        try {
            $response = $this->client->send($request);

            $this->response = $response;

            return $this->parseResponse($response);
        } catch (ClientException $exception) {

            $this->response = $exception->getResponse();

            if ($this->response->getStatusCode() === 404) {
                return new Collection;
            }

            throw $exception;
        }
    }
178305
protected function doRequest($request)
    {
        if (!$this->firstRequest) {
            $this->initialize($request);
        }
        $this->firstRequest = false;

        $this->applyBindings();
        $this->applyContextualBindings();
        $this->applyInstances();
        $this->applyApplicationHandlers();

        $request = Request::createFromBase($request);
        $response = $this->kernel->handle($request);
        $this->app->make('Illuminate\Contracts\Http\Kernel')->terminate($request, $response);

        return $response;
    }
1339907
protected function handleRequest(Request $request)
    {
        if ($this->isLaravel()) {
            return $this->getKernel()->handle($request);
        }

        return $this->getApplication()->dispatch($request);
    }
347195
public function execute($request)
  {
    if ($request instanceof Request) {
      $request->setUserAgent(
          $this->getApplicationName()
          . " " . self::USER_AGENT_SUFFIX
          . $this->getLibraryVersion()
      );
      if (!$this->getClassConfig("Request", "disable_gzip")) {
        $request->enableGzip();
      }
      $request->maybeMoveParametersToBody();
      return REST::execute($this, $request);
    } else if ($request instanceof Batch) {
      return $request->execute();
    } else {
      throw new Exception("Do not know how to execute this type of object.");
    }
  }
822522
public function sendRequest(Request $request)
    {
        try {
            $rawResponse = $this->processRequest($request);
        } catch (Exception $exception) {
            if ($this->successor) {
                return $this->successor->sendRequest($request);
            }
            throw $exception;
        }

        $response = new Response($request, $rawResponse);

        if ($response->isError()) {
            throw $response->getThrownException();
        }

        return $response;
    }
982827
public function dispatch(Request $request)
    {
        $pathInfo = $request->getPathInfo();
        $method   = $request->getMethod();

        $route = $this->collection->find($method, $pathInfo);

        if ( ! $route) {
            throw new \Exception('Route not found !');
        }

        return $this->dispatcher->dispatch($route);
    }
502384
public function send(AbstractRequest $request)
    {
        try {

            $client = $this->client;
            $config = $this->config;

            if(false === $config->isValid()) {
                throw new \Exception("Configuration is not valid.");
            }

            if(is_null($client)) {
                throw new \Exception('Zend\Http\Client must be set and must be valid.');
            }

            if(false === $request->isValid()) {
                throw new \Exception(get_class($request) . " is invalid.");
            }

            $client->setMethod('POST');
            $client->setUri(new \Zend\Uri\Http($config->getEndpoint()));
            $client->setRawBody($config . $request);

            $httpResponse = $client->send();

            $response = Response::factory($request->getMethod(), $httpResponse->getBody());

        } catch(\Exception $e) {

            $response = new Response();
            $response->addErrorMessage($e->getMessage());
        }

        return $response;
    }
1244529
public static function handleOAuthError(Request $request)
    {
        $error = null;

        // Try to parse content if error was not in request query
        if ($request->query->has('error')) {
            $content = json_decode($request->getContent(), true);
            if (isset($content['error']) && JSON_ERROR_NONE === json_last_error()) {
                if (isset($content['error']['message'])) {
                    throw new AuthenticationException($content['error']['message']);
                }

                if (isset($content['error']['code'])) {
                    $error = $content['error']['code'];
                } elseif (isset($content['error']['error-code'])) {
                    $error = $content['error']['error-code'];
                } else {
                    $error = $request->query->get('error');
                }
            }
        } elseif ($request->query->has('oauth_problem')) {
            $error = $request->query->get('oauth_problem');
        }

        if (null !== $error) {
            if (isset(static::$translatedOAuthErrors[$error])) {
                $error = static::$translatedOAuthErrors[$error];
            } else {
                $error = sprintf('Unknown OAuth error: "%s".', $error);
            }

            throw new AuthenticationException($error);
        }
    }
1358710
public function registerAction(Request $request): Response
    {
        $content = $request->getContent();
        $content = \json_decode($content, true);

        /** @var TenantInterface $tenant */
        /** @noinspection PhpUndefinedMethodInspection */
        $tenant = $this->em->getRepository($this->tenantClass)->findOneByClientKey($content['clientKey']);
        if ($tenant !== null) {
            try {
                $authorizationHeaderArray = \explode(' ', $request->headers->get('authorization'));
                if (\count($authorizationHeaderArray) <= 1) {
                    throw new \InvalidArgumentException('Bad authorization header');
                }

                $jwt = $authorizationHeaderArray[1];
                JWT::decode($jwt, $tenant->getSharedSecret(), ['HS256']);
            } catch (\Throwable $e) {
                $this->logger->error($e->getMessage(), ['exception' => $e]);

                return new Response('Unauthorized', 401);
            }
        } else {
            $tenantClass = $this->tenantClass;
            $tenant = new $tenantClass();
        }

        $tenant
            ->setAddonKey($content['key'])
            ->setClientKey($content['clientKey'])
            ->setPublicKey($content['publicKey'])
            ->setSharedSecret($content['sharedSecret'])
            ->setServerVersion($content['serverVersion'])
            ->setPluginsVersion($content['pluginsVersion'])
            ->setBaseUrl($content['baseUrl'])
            ->setProductType($content['productType'])
            ->setDescription($content['description'])
            ->setEventType($content['eventType'])
        ;

        if (\array_key_exists('oauthClientId', $content)) {
            $tenant->setOauthClientId($content['oauthClientId']);
        }

        $this->em->persist($tenant);
        $this->em->flush();

        return new Response('OK', 200);
    }
1089221
public function receive(DispatcherRequestInterface $request)
    {
        //Set the headers
        $headers = array();
        foreach ($_SERVER as $key => $value)
        {
            if ($value && strpos($key, 'HTTP_') === 0)
            {
                // Cookies are handled using the $_COOKIE superglobal
                if (strpos($key, 'HTTP_COOKIE') === 0) {
                    continue;
                }

                $headers[substr($key, 5)] = $value;
            }
            elseif ($value && strpos($key, 'CONTENT_') === 0)
            {
                $name = substr($key, 8); // Content-
                $name = 'Content-' . (($name == 'MD5') ? $name : ucfirst(strtolower($name)));

                $headers[$name] = $value;
            }
        }

        $request->getHeaders()->add($headers);
    }
223650
protected function doRequest($request)
    {
        if (!$this->firstRequest) {
            $this->initialize($request);
        }
        $this->firstRequest = false;

        $this->applyBindings();
        $this->applyContextualBindings();
        $this->applyInstances();
        $this->applyApplicationHandlers();

        $request = Request::createFromBase($request);
        $response = $this->kernel->handle($request);

        $method = new \ReflectionMethod(get_class($this->app), 'callTerminableMiddleware');
        $method->setAccessible(true);
        $method->invoke($this->app, $response);

        return $response;
    }
846472
public function handle($request)
    {
        $this->loadAuthManager();
        
        try {
            $response = $this->sendRequestThroughRouter($request);
            $response = $response->getContent();
            
            $json = json_decode($response, true);
            if (json_last_error() == JSON_ERROR_NONE) {
                $response = $json;
            }
        } catch (Exception $e) {
            if ($e instanceof NotFoundHttpException) {
                $response = $e;
            } else {
                throw $e;
            }
        }
        
        $this->app['events']->fire('wskernel.handled', [$request, $response]);
        
        return $response;
    }
1239118
public function handleAction(Request $request): Response
    {
        $extras = $request->request->get('extras', []);

        if (!$this->hashHandler->verify($extras['worker'] ?? [], false)) {
            return JsonResponse::create(['invalid' => true, 'message' => 'Invalid hash verify.'], 500);
        }

        try {
            $result = $this->bus->dispatch($this->decoder->decode([
                'body' => $request->getContent(),
                'headers' => ['type' => $request->headers->get('x-chang-msg-type')],
            ])->with(new ReceivedStamp()));
        } catch (\Exception $e) {
            return JsonResponse::create(['message' => $e->getMessage()], 500);
        }

        $this->hashHandler->flush();

        if ($result instanceof AbstractMessage && $result->isExpired()) {
            return JsonResponse::create(['expired' => true, 'message' => 'Message was expired.'], 500);
        }

        return JsonResponse::create([], 200);
    }
875365
public function handle(Request $request)
    {
        try {
            $restRequest = new RestRequest($this->config, $request->getMethod(), $request->getUri(), $request->getContent());
            $restResponse = $this->adapter->processRequest($restRequest);
        } catch (\Exception $e) {
            if (true === $this->debugEnabled()) {
                throw $e;
            }
            $restResponse = $this->adapter->handleException($e);
        }
        return new Response($restResponse->getContent(), $restResponse->getStatus(), $restResponse->getHeaders());
    }
151013
private function resolveErrorHandlerFromAcceptHeader(Request $request): callable
    {
        // Try to find an error handler for one of the accepted content types
        $accepts = $request->hasHeader('Accept') ? $request->getHeaderLine('Accept') : $this->defaultContentType;
        /** @var array $accepts */
        $accepts = explode(',', $accepts);
        foreach ($accepts as $accept) {
            if (! $this->errorHandlerManager->has($accept)) {
                continue;
            }

            return $this->errorHandlerManager->get($accept);
        }

        // If it wasn't possible to find an error handler for accepted content type, use default one if registered
        if ($this->errorHandlerManager->has($this->defaultContentType)) {
            return $this->errorHandlerManager->get($this->defaultContentType);
        }

        // It wasn't possible to find an error handler
        throw new InvalidArgumentException(sprintf(
            'It wasn\'t possible to find an error handler for ["%s"] content types. '
            . 'Make sure you have registered at least the default "%s" content type',
            implode('", "', $accepts),
            $this->defaultContentType
        ));
    }