Esempio n. 1
0
 /**
  * Call the middleware
  */
 public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
 {
     $scheme = $request->getUri()->getScheme();
     $host = $request->getUri()->getHost();
     /* If rules say we should not authenticate call next and return. */
     if (false === $this->shouldAuthenticate($request)) {
         return $next($request, $response);
     }
     /* HTTP allowed only if secure is false or server is in relaxed array. */
     if ("https" !== $scheme && true === $this->options["secure"]) {
         if (!in_array($host, $this->options["relaxed"])) {
             $message = sprintf("Insecure use of middleware over %s denied by configuration.", strtoupper($scheme));
             throw new \RuntimeException($message);
         }
     }
     /* If token cannot be found return with 401 Unauthorized. */
     if (false === ($token = $this->fetchToken($request))) {
         return $this->error($request, $response, ["message" => $this->message])->withStatus(401);
     }
     /* If token cannot be decoded return with 401 Unauthorized. */
     if (false === ($decoded = $this->decodeToken($token))) {
         return $this->error($request, $response, ["message" => $this->message])->withStatus(401);
     }
     /* If callback returns false return with 401 Unauthorized. */
     if (is_callable($this->options["callback"])) {
         $params = ["decoded" => $decoded];
         if (false === $this->options["callback"]($request, $response, $params)) {
             return $this->error($request, $response, ["message" => $this->message || "Callback returned false"])->withStatus(401);
         }
     }
     /* Everything ok, call next middleware and return. */
     return $next($request, $response);
 }
Esempio n. 2
0
 /**
  * @return string|null
  */
 public function getLastRequestPath()
 {
     if (is_null($this->lastRequest)) {
         return null;
     }
     return $this->lastRequest->getUri();
 }
 /**
  * @param \Psr\Http\Message\RequestInterface $request
  * @param \Psr\Http\Message\ResponseInterface $response
  *
  * @return string
  */
 protected function describe(RequestInterface $request, ResponseInterface $response = null)
 {
     if (!$response) {
         return sprintf('%s %s failed', $request->getMethod(), $request->getUri());
     }
     return sprintf('%s %s returned %s %s', $request->getMethod(), $request->getUri(), $response->getStatusCode(), $response->getReasonPhrase());
 }
Esempio n. 4
0
 public function signRequest(RequestInterface $request, CredentialsInterface $credentials)
 {
     $params = Psr7\parse_query($request->getBody()->__toString());
     $params['SignatureVersion'] = '2';
     $params['SignatureMethod'] = 'HmacSHA256';
     $params['AWSAccessKeyId'] = $credentials->getAccessKeyId();
     if ($credentials->getSecurityToken()) {
         $params['MWSAuthToken'] = $credentials->getSecurityToken();
     }
     $params['Timestamp'] = gmdate(self::ISO8601_BASIC);
     ksort($params);
     $canonicalizedQueryString = $this->getCanonicalizedQuery($params);
     $stringToSign = implode("\n", [$request->getMethod(), $request->getUri()->getHost(), $request->getUri()->getPath(), $canonicalizedQueryString]);
     // calculate HMAC with SHA256 and base64-encoding
     $signature = base64_encode(hash_hmac('sha256', $stringToSign, $credentials->getSecretKey(), TRUE));
     // encode the signature for the request
     $signature = str_replace('%7E', '~', rawurlencode($signature));
     $signature = str_replace('+', '%20', $signature);
     $signature = str_replace('*', '%2A', $signature);
     $queryString = $canonicalizedQueryString . "&Signature=" . $signature;
     if ($request->getMethod() === 'POST') {
         return new Request('POST', $request->getUri(), ['Content-Length' => strlen($queryString), 'Content-Type' => 'application/x-www-form-urlencoded'], $queryString);
     } else {
         return new Request('GET', $request->getUri()->withQuery($queryString));
     }
 }
 /**
  * @return string
  */
 public function getUri()
 {
     if (!$this->request) {
         return null;
     }
     return (string) $this->request->getUri();
 }
Esempio n. 6
0
 /**
  * Forward the request to the target url and return the response.
  *
  * @param  string $target
  * @throws UnexpectedValueException
  * @return Response
  */
 public function to($target)
 {
     if (is_null($this->request)) {
         throw new UnexpectedValueException('Missing request instance.');
     }
     $target = new Uri($target);
     // Overwrite target scheme and host.
     $uri = $this->request->getUri()->withScheme($target->getScheme())->withHost($target->getHost());
     // Check for custom port.
     if ($port = $target->getPort()) {
         $uri = $uri->withPort($port);
     }
     // Check for subdirectory.
     if ($path = $target->getPath()) {
         $uri = $uri->withPath(rtrim($path, '/') . '/' . ltrim($uri->getPath(), '/'));
     }
     $request = $this->request->withUri($uri);
     $stack = $this->filters;
     $stack[] = function (RequestInterface $request, ResponseInterface $response, callable $next) {
         $response = $this->adapter->send($request);
         return $next($request, $response);
     };
     $relay = (new RelayBuilder())->newInstance($stack);
     return $relay($request, new Response());
 }
Esempio n. 7
0
 /**
  * {@inheritdoc}
  */
 public function handleRequest(RequestInterface $request, callable $next, callable $first)
 {
     if ($this->replace || $request->getUri()->getHost() === '') {
         $uri = $request->getUri()->withHost($this->host->getHost())->withScheme($this->host->getScheme())->withPort($this->host->getPort());
         $request = $request->withUri($uri);
     }
     return $next($request);
 }
 /**
  * @param RequestInterface $request
  *
  * @return string|null
  */
 protected function processing(RequestInterface $request)
 {
     $key = sprintf('%s?%s', $request->getUri()->getPath(), $request->getUri()->getQuery());
     if ($request->getMethod() == 'GET' && isset($this->data[$key])) {
         return $this->data[$key];
     }
     return null;
 }
Esempio n. 9
0
 /**
  * @param $champ
  * @return mixed
  */
 public function getGet($champ)
 {
     parse_str($this->request->getUri()->getQuery(), $tab);
     if (!isset($tab[$champ])) {
         return null;
     }
     return $tab[$champ];
 }
 /**
  * Converts default GET request to a POST request
  *
  * Avoiding length restriction in query
  *
  * @param RequestInterface $r GET request to be converted
  * @return RequestInterface $req converted POST request
  */
 public static function convertGetToPost(RequestInterface $r)
 {
     if ($r->getMethod() === 'POST') {
         return $r;
     }
     $query = $r->getUri()->getQuery();
     $req = $r->withMethod('POST')->withBody(Psr7\stream_for($query))->withHeader('Content-Length', strlen($query))->withHeader('Content-Type', 'application/x-www-form-urlencoded')->withUri($r->getUri()->withQuery(''));
     return $req;
 }
Esempio n. 11
0
 /**
  * {@inheritdoc}
  */
 public function __invoke(Request $request, Response $response, callable $next)
 {
     // Prepare default URL
     // TODO: Improve URI modification
     $uri = $this->uri;
     $uri = $uri->withPath($uri->getPath() . '/' . ltrim($request->getUri()->getPath(), '/'));
     $uri = $uri->withQuery($request->getUri()->getQuery());
     $request = $request->withUri($uri);
     return $next($request, $response);
 }
 /**
  * @param array $claims
  * @return string
  */
 public function getToken(array $claims = [])
 {
     $issuer = (string) $this->request->getUri();
     $issued_at = $this->config->getTimestamp();
     $expiration = $issued_at + $this->config->getTtl();
     $key = $this->config->getPublicKey();
     $algorithm = $this->config->getAlgorithm();
     $claims += ['iss' => $issuer, 'iat' => $issued_at, 'exp' => $expiration];
     return JWT::encode($claims, $key, $algorithm);
 }
 /**
  * Inject credentials information into the query parameters
  *
  * @param RequestInterface $request
  * @param array            $options
  *
  * @return GuzzleResponseInterface
  */
 public function __invoke(RequestInterface $request, array $options)
 {
     if ($request->getUri()->getScheme() == 'https' && $options['auth'] == static::AUTH_NAME) {
         $uri = Uri::withQueryValue($request->getUri(), 'client_id', $this->userKey ?: $this->apiKey);
         $uri = Uri::withQueryValue($uri, 'client_secret', $this->secret);
         $request = $request->withUri($uri);
     }
     $fn = $this->nextHandler;
     return $fn($request, $options);
 }
Esempio n. 14
0
 protected function getPath(RequestInterface $request)
 {
     $path = $this->path . DIRECTORY_SEPARATOR . strtolower($request->getMethod()) . DIRECTORY_SEPARATOR . $request->getUri()->getHost() . DIRECTORY_SEPARATOR;
     $rpath = $request->getUri()->getPath();
     if ($rpath && $rpath !== '/') {
         $rpath = substr($rpath, 0, 1) === '/' ? substr($rpath, 1) : $rpath;
         $rpath = substr($rpath, -1, 1) === '/' ? substr($rpath, 0, -1) : $rpath;
         $path .= str_replace("/", "_", $rpath) . DIRECTORY_SEPARATOR;
     }
     return $path;
 }
 /**
  * @param array $claims
  * @return string
  */
 public function getToken(array $claims = [])
 {
     $issuer = (string) $this->request->getUri();
     $issued_at = $this->config->getTimestamp();
     $expiration = $issued_at + $this->config->getTtl();
     $key = $this->config->getPrivateKey();
     foreach ($claims as $name => $value) {
         $this->builder->set($name, $value);
     }
     $token = $this->builder->setIssuer($issuer)->setIssuedAt($issued_at)->setExpiration($expiration)->sign($this->signer, $key)->getToken();
     return (string) $token;
 }
Esempio n. 16
0
 public function send(RequestInterface $request)
 {
     switch ($request->getUri()->getPath()) {
         case '/documents/1':
             if ('GET' === $request->getMethod()) {
                 return new Response(200, ['Content-Type' => 'application/hal+json'], file_get_contents(__DIR__ . '/fixtures/documents_1.json'));
             }
             break;
         case '/documents/2':
             if ('GET' === $request->getMethod()) {
                 return new Response(200, ['Content-Type' => 'application/hal+json'], file_get_contents(__DIR__ . '/fixtures/documents_2.json'));
             }
             break;
         case '/documents/3':
             if ('GET' === $request->getMethod()) {
                 return new Response(200, ['Content-Type' => 'application/hal+json'], file_get_contents(__DIR__ . '/fixtures/documents_3.json'));
             }
             break;
         case '/documents/4':
             if ('DELETE' === $request->getMethod()) {
                 return new Response(204, ['Content-Type' => 'text/html']);
             }
             if ('PUT' === $request->getMethod()) {
                 if ('{"title":"Test 4 changed","body":"Lorem ipsum"}' === $request->getBody()->getContents()) {
                     return new Response(200, ['Content-Type' => 'application/hal+json'], file_get_contents(__DIR__ . '/fixtures/documents_4_changed.json'));
                 }
             }
             if ('GET' === $request->getMethod()) {
                 return new Response(200, ['Content-Type' => 'application/hal+json'], file_get_contents(__DIR__ . '/fixtures/documents_4.json'));
             }
             break;
         case '/documents':
             if ('POST' === $request->getMethod()) {
                 if ('{"title":"Test 4","body":"Lorem ipsum"}' === $request->getBody()->getContents()) {
                     return new Response(201, ['Location' => '/documents/4']);
                 }
             }
             if ('GET' === $request->getMethod()) {
                 return new Response(200, ['Content-Type' => 'application/hal+json'], file_get_contents(__DIR__ . '/fixtures/documents.json'));
             }
             break;
         case '':
             if ('GET' === $request->getMethod()) {
                 return new Response(200, ['Content-Type' => 'application/hal+json'], file_get_contents(__DIR__ . '/fixtures/root.json'));
             }
             break;
         default:
             return new Response(404);
     }
     return new Response(405, ['Content-Type' => 'text/plain'], sprintf('No route found for "%s %s": Method Not Allowed', $request->getUri()->getPath(), $request->getMethod()));
 }
Esempio n. 17
0
 /**
  * Forward the request to the target url and return the response.
  *
  * @param  string $target
  * @throws UnexpectedValueException
  * @return Response
  */
 public function to($target)
 {
     if (is_null($this->request)) {
         throw new UnexpectedValueException('Missing request instance.');
     }
     $uri = $this->request->getUri()->withScheme(parse_url($target, PHP_URL_SCHEME))->withHost(parse_url($target, PHP_URL_HOST));
     $request = $this->request->withUri($uri);
     $stack = $this->filters;
     $stack[] = function (RequestInterface $request, ResponseInterface $response, callable $next) use($target) {
         $response = $this->adapter->send($request, $target);
         return $next($request, $response);
     };
     $relay = (new RelayBuilder())->newInstance($stack);
     return $relay($request, new Response());
 }
Esempio n. 18
0
 /**
  * Returns the filename of the response file.
  *
  * @param RequestInterface $request
  * @param string           $indexExt
  *
  * @return string
  */
 private function getFilename(RequestInterface $request, $indexExt = 'html')
 {
     $path = $this->getPath($request->getUri()->getPath());
     $parts = pathinfo($path);
     $path = isset($parts['dirname']) ? $parts['dirname'] : '';
     $filename = isset($parts['basename']) ? $parts['basename'] : '';
     //if it's a directory, append the index file
     if (empty($parts['extension'])) {
         $filename .= "/index.{$indexExt}";
     }
     if ($this->appendQuery && $request->getUri()->getQuery()) {
         $filename .= '?' . urlencode($request->getUri()->getQuery());
     }
     return Helpers::joinPath($this->directory, $path, $filename);
 }
Esempio n. 19
0
 public function __invoke(Request $request, Response $response, callable $next)
 {
     $uri = $request->getUri();
     $path = $uri->getPath();
     $valid_path = array('login', 'signup');
     $currentUser = $this->settings->get('current_user');
     if (is_null($currentUser)) {
         $uri = $request->getUri();
         if (!array_search($path, $valid_path)) {
             // Redirect to login
             return $response->withStatus(302)->withHeader('Location', $uri->withPath('login'));
         }
     }
     return $next($request, $response, $next);
 }
Esempio n. 20
0
 /**
  * Send a request to the server and return a Response object with the response.
  *
  * @param   RequestInterface $request The request object to send.
  *
  * @return  ResponseInterface
  *
  * @since   2.1
  */
 public function request(RequestInterface $request)
 {
     $uri = $request->getUri()->withPath(null)->withQuery(null)->withFragment(null);
     $uri = $uri . $request->getRequestTarget();
     $request = $request->withRequestTarget($uri);
     return $this->doRequest($request);
 }
Esempio n. 21
0
 /**
  * {@inheritdoc}
  */
 public function request(RequestInterface $request)
 {
     $url = (string) $request->getUri();
     $body = $request->getBody();
     $body->seek(0);
     $headers = $request->getHeaders();
     $headers['Accept'] = 'application/json';
     $headers['Content-Type'] = 'application/json';
     $req = $this->guzzle->createRequest($request->getMethod(), $url);
     $req->setHeaders($headers);
     $req->setBody(GStream::factory($body->getContents()));
     try {
         $res = $this->guzzle->send($req);
     } catch (RequestException $e) {
         // Guzzle will throw exceptions for 4xx and 5xx responses, so we catch
         // them here and quietly get the response object.
         $res = $e->getResponse();
         if (!$res) {
             throw $e;
         }
     }
     $response = (new Response(new Stream('php://memory', 'w')))->withStatus($res->getStatusCode(), $res->getReasonPhrase());
     $response->getBody()->write((string) $res->getBody());
     return $response;
 }
Esempio n. 22
0
 /**
  * Factory method to create a new exception with a normalized error message
  *
  * @param RequestInterface  $request  Request
  * @param ResponseInterface $response Response received
  * @param \Exception        $previous Previous exception
  * @param array             $ctx      Optional handler context.
  *
  * @return self
  */
 public static function create(RequestInterface $request, ResponseInterface $response = null, \Exception $previous = null, array $ctx = [])
 {
     if (!$response) {
         return new self('Error completing request', $request, null, $previous, $ctx);
     }
     $level = (int) floor($response->getStatusCode() / 100);
     if ($level === 4) {
         $label = 'Client error';
         $className = __NAMESPACE__ . '\\ClientException';
     } elseif ($level === 5) {
         $label = 'Server error';
         $className = __NAMESPACE__ . '\\ServerException';
     } else {
         $label = 'Unsuccessful request';
         $className = __CLASS__;
     }
     $uri = $request->getUri();
     $uri = static::obfuscateUri($uri);
     // Server Error: `GET /` resulted in a `404 Not Found` response:
     // <html> ... (truncated)
     $message = sprintf('%s: `%s` resulted in a `%s` response', $label, $request->getMethod() . ' ' . $uri, $response->getStatusCode() . ' ' . $response->getReasonPhrase());
     $summary = static::getResponseBodySummary($response);
     if ($summary !== null) {
         $message .= ":\n{$summary}\n";
     }
     return new $className($message, $request, $response, $previous, $ctx);
 }
Esempio n. 23
0
 /**
  * {@inheritdoc}
  *
  * @api
  */
 public function matches(RequestInterface $request)
 {
     if ($this->schemes && !in_array($request->getUri()->getScheme(), $this->schemes)) {
         return false;
     }
     if ($this->methods && !in_array($request->getMethod(), $this->methods)) {
         return false;
     }
     if (null !== $this->path && !preg_match('{' . $this->path . '}', rawurldecode($request->getUri()->getPath()))) {
         return false;
     }
     if (null !== $this->host && !preg_match('{' . $this->host . '}i', $request->getUri()->getHost())) {
         return false;
     }
     return true;
 }
Esempio n. 24
0
 /**
  * Check the current url for oauth paths
  *
  * @param  RequestInterface  $request  PSR7 request object
  * @param  ResponseInterface $response PSR7 response object
  *
  * @return ResponseInterface|false PSR7 response object
  */
 private function checkForOAuthPaths(RequestInterface $request, ResponseInterface $response)
 {
     $path = $request->getUri()->getPath();
     if (!is_string($path)) {
         return false;
     }
     // this matches the request to authenticate for an oauth provider
     if (1 === preg_match($this->getAuthRouteRegex(), $path, $matches)) {
         // validate we have an allowed oAuthServiceType
         if (!in_array($matches['oAuthServiceType'], $this->oAuthProviders)) {
             throw new Exception("Unknown oAuthServiceType");
         }
         // validate the return url
         parse_str($_SERVER['QUERY_STRING'], $query);
         if (!array_key_exists('return', $query) || filter_var($query['return'], FILTER_VALIDATE_URL) === false) {
             throw new Exception("Invalid return url");
         }
         $_SESSION['oauth_return_url'] = $query['return'];
         $url = $this->oAuthFactory->getOrCreateByType($matches['oAuthServiceType'])->getAuthorizationUri();
         return $response->withStatus(302)->withHeader('Location', $url);
     } elseif (1 === preg_match($this->getCallbackRouteRegex(), $path, $matches)) {
         // this matches the request to post-authentication for an oauth provider
         if (!in_array($matches['oAuthServiceType'], $this->oAuthProviders)) {
             throw new Exception("Unknown oAuthServiceType");
         }
         $service = $this->oAuthFactory->getOrCreateByType($matches['oAuthServiceType']);
         // turn our code into a token that's stored internally
         $service->requestAccessToken($request->getParam('code'));
         // validates and creates the user entry in the db if not already exists
         $user = $this->userService->createUser($service);
         // set our token in the header and then redirect to the client's chosen url
         return $response->withStatus(200)->withHeader('Authorization', 'token ' . $user->token)->withHeader('Location', $_SESSION['oauth_return_url']);
     }
     return false;
 }
Esempio n. 25
0
 public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
 {
     $path = $request->getUri()->getPath();
     if (!isset($this->commands[$path])) {
         return $next($request, $response);
     }
     if ($request->getMethod() !== 'POST') {
         return $response->withStatus(405);
     }
     try {
         $payload = json_decode($request->getBody(), true);
         if ($payload === null) {
             $payload = [];
         }
         $command = $this->commands[$path];
         if (!is_callable($command)) {
             throw new \RuntimeException("Command associated with the path {$path} is not callable");
         }
         $command = call_user_func_array($command, [$payload]);
         $this->commandBus->dispatch($command);
         return $response->withStatus(202);
     } catch (CommandDispatchException $dispatchException) {
         $e = $dispatchException->getFailedCommandDispatch()->getException();
         return $this->populateError($response, $e);
     } catch (\Exception $e) {
         return $this->populateError($response, $e);
     }
 }
Esempio n. 26
0
 /**
  * @param Request $request
  *
  * @return Response
  */
 public function __invoke(Request $request)
 {
     $options = [];
     // Headers
     $headerLines = [];
     foreach ($request->getHeaders() as $name => $values) {
         $headerLines[] = sprintf('%s: %s', $name, implode(', ', $values));
     }
     $options[CURLOPT_HTTPHEADER] = $headerLines;
     // Url
     $options[CURLOPT_URL] = (string) $request->getUri();
     switch ($request->getMethod()) {
         case 'HEAD':
             $options[CURLOPT_NOBODY] = true;
             break;
         case 'GET':
             $options[CURLOPT_HTTPGET] = true;
             break;
         case 'POST':
             $options[CURLOPT_POST] = true;
             $options[CURLOPT_POSTFIELDS] = (string) $request->getBody();
             // Don't duplicate the Content-Length header
             $request = $request->withoutHeader('Content-Length');
             $request = $request->withoutHeader('Transfer-Encoding');
             break;
         case 'PUT':
             // Write to memory/temp
             $file = fopen('php://temp/' . spl_object_hash($request), 'w+');
             $bytes = fwrite($file, (string) $request->getBody());
             rewind($file);
             $options[CURLOPT_PUT] = true;
             $options[CURLOPT_INFILE] = $file;
             $options[CURLOPT_INFILESIZE] = $bytes;
             $request = $request->withoutHeader('Content-Length');
             break;
         default:
             $options[CURLOPT_CUSTOMREQUEST] = $request->getMethod();
     }
     // If the Expect header is not present, prevent curl from adding it
     if (!$request->hasHeader('Expect')) {
         $options[CURLOPT_HTTPHEADER][] = 'Expect:';
     }
     // cURL sometimes adds a content-type by default. Prevent this.
     if (!$request->hasHeader('Content-Type')) {
         $options[CURLOPT_HTTPHEADER][] = 'Content-Type:';
     }
     list($body, $headerLines) = $this->execute($options);
     $headerLines = preg_split("#\r\n#", $headerLines, -1, PREG_SPLIT_NO_EMPTY);
     $headers = [];
     // Extract the version and status from the first header
     preg_match('#HTTP/(\\d\\.\\d)\\s(\\d\\d\\d)\\s(.*)#', array_shift($headerLines), $matches);
     array_shift($matches);
     list($protocolVersion, $statusCode, $reasonPhrase) = $matches;
     foreach ($headerLines as $line) {
         list($name, $values) = preg_split('#\\s*:\\s*#', $line, 2, PREG_SPLIT_NO_EMPTY);
         $headers[$name] = preg_split('#\\s*,\\s*#', $values, -1, PREG_SPLIT_NO_EMPTY);
     }
     $response = new \GuzzleHttp\Psr7\Response($statusCode, $headers, $body, $protocolVersion, $reasonPhrase);
     return $response;
 }
Esempio n. 27
0
 /**
  * Execute the middleware.
  *
  * @param RequestInterface  $request
  * @param ResponseInterface $response
  * @param callable          $next
  *
  * @return ResponseInterface
  */
 public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
 {
     $uri = $request->getUri();
     $path = $uri->getPath();
     //Test basePath
     if (!$this->testBasePath($path)) {
         return $next($request, $response);
     }
     //Add/remove slash
     if ($this->addSlash) {
         if (strlen($path) > 1 && substr($path, -1) !== '/' && !pathinfo($path, PATHINFO_EXTENSION)) {
             $path .= '/';
         }
     } else {
         if (strlen($path) > 1 && substr($path, -1) === '/') {
             $path = substr($path, 0, -1);
         }
     }
     //Ensure the path has one "/"
     if (empty($path) || $path === $this->basePath) {
         $path .= '/';
     }
     //redirect
     if (is_int($this->redirectStatus) && $uri->getPath() !== $path) {
         return self::getRedirectResponse($this->redirectStatus, $uri->withPath($path), $response);
     }
     return $next($request->withUri($uri->withPath($path)), $response);
 }
 /**
  * Create a fingerprint for each request.
  *
  * As it is for mocking (and not for real caching), ignore some
  * characteristics like the 'User-Agent' to avoid stale cache
  * when updating PHP or Guzzle.
  *
  * @param RequestInterface $request
  * @param bool             $withHost
  *
  * @return string The path to the mock file
  */
 public function getPath(RequestInterface $request, $withHost = true)
 {
     $headers = $request->getHeaders();
     foreach ($headers as $name => $values) {
         if (in_array($name, $this->headersBlacklist)) {
             unset($headers[$name]);
         }
     }
     $fingerprint = md5(serialize(['method' => $request->getMethod(), 'path' => $request->getUri()->getPath(), 'query' => $request->getUri()->getQuery(), 'user_info' => $request->getUri()->getUserInfo(), 'port' => $request->getUri()->getPort(), 'scheme' => $request->getUri()->getScheme(), 'headers' => $headers]));
     if (true === $withHost) {
         $path = sprintf('%s_%s_%s____%s', str_pad($request->getMethod(), 6, '_'), $request->getUri()->getHost(), urldecode(ltrim($request->getUri()->getPath(), '/') . '-' . $request->getUri()->getQuery()), $fingerprint);
     } else {
         $path = sprintf('%s_%s____%s', str_pad($request->getMethod(), 6, '_'), urldecode(ltrim($request->getUri()->getPath(), '/') . '-' . $request->getUri()->getQuery()), $fingerprint);
     }
     return $this->storagePath . '/' . preg_replace('/[^a-zA-Z0-9_+=@\\-\\?\\.]/', '-', $path) . '.txt';
 }
Esempio n. 29
0
 /**
  * Execute the middleware.
  *
  * @param RequestInterface  $request
  * @param ResponseInterface $response
  * @param callable          $next
  *
  * @return ResponseInterface
  */
 public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
 {
     $uri = $request->getUri();
     $path = $this->getBasePath($uri->getPath());
     $request = $request->withUri($uri->withPath($path));
     return $next($request, $response);
 }
Esempio n. 30
0
 /**
  * @param RequestInterface $request
  * @return ResponseInterface
  */
 public function send($request)
 {
     /**
      * var \GuzzleHttp\Message\Response $response
      */
     $headers = $request->getHeaders();
     if (!empty($this->append_headers)) {
         $headers = array_merge($headers, $this->append_headers);
     }
     $opt = [];
     if (!empty($this->basicAuth)) {
         $opt['auth'] = $this->basicAuth;
     }
     if (!empty($headers)) {
         $opt['headers'] = $headers;
     }
     $body = $request->getBody();
     if ($body !== null) {
         $opt['body'] = $body;
     }
     $g4request = $this->getClient()->createRequest($request->getMethod(), $request->getUri(), $opt);
     try {
         $response = $this->getClient()->send($g4request);
         return new Response($response->getStatusCode(), $response->getHeaders(), $response->getBody());
     } catch (\GuzzleHttp\Exception\RequestException $ex) {
         $ex_request = $ex->getRequest();
         $ex_response = $ex->getResponse();
         throw new RequestException($ex->getMessage(), $ex_request ? new Request($ex_request->getMethod(), $ex_request->getUrl(), $ex_request->getHeaders(), $ex_request->getBody()) : null, $ex_response ? new Response($ex_response->getStatusCode(), $ex_response->getHeaders(), $ex_response->getBody()) : null, $ex);
     }
 }