/**
  * 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;
 }
 /**
  * @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());
 }
 /**
  * Starts the profiling.
  * @param RequestInterface $request
  */
 public function enter(RequestInterface $request = null)
 {
     $this->starts = ['wt' => microtime(true), 'mu' => memory_get_usage(), 'pmu' => memory_get_peak_usage()];
     if ($request) {
         $this->request = ['method' => $request->getMethod(), 'url' => (string) $request->getUri(), 'body' => (string) $request->getBody()];
     }
 }
Example #4
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);
 }
 /**
  * @return string
  */
 public function getUri()
 {
     if (!$this->request) {
         return null;
     }
     return (string) $this->request->getUri();
 }
 /**
  * @param ServerRequestInterface $request  PSR7 Request.
  * @param ResponseInterface      $response PSR7 Response.
  * @return ResponseInterface
  */
 public function run(RequestInterface $request, ResponseInterface $response)
 {
     $widgetType = $request->getParam('widget_type');
     $widgetOptions = $request->getParam('widget_options');
     if (!$widgetType) {
         $this->setSuccess(false);
         return $response->withStatus(400);
     }
     try {
         $widget = $this->widgetFactory->create($widgetType);
         $widget->setView($this->widgetView);
         if (is_array($widgetOptions)) {
             $widget->setData($widgetOptions);
         }
         $widgetHtml = $widget->renderTemplate($widgetType);
         $widgetId = $widget->widgetId();
         $this->setWidgetHtml($widgetHtml);
         $this->setWidgetId($widgetId);
         $this->setSuccess(true);
         return $response;
     } catch (Exception $e) {
         $this->addFeedback('error', sprintf('An error occured reloading the widget: "%s"', $e->getMessage()));
         $this->addFeedback('error', $e->getMessage());
         $this->setSuccess(false);
         return $response->withStatus(500);
     }
 }
 /**
  * @param RequestInterface $request
  * @param string $name
  * @return string
  */
 public function getAttribute(RequestInterface $request, $name)
 {
     if (!$request instanceof ServerRequestInterface) {
         throw new \InvalidArgumentException('Request is not of type ' . ServerRequestInterface::class);
     }
     return $request->getAttribute($name);
 }
 /**
  * Note that the lost-password action should never change status code and always return 200.
  *
  * @param RequestInterface  $request  A PSR-7 compatible Request instance.
  * @param ResponseInterface $response A PSR-7 compatible Response instance.
  * @return ResponseInterface
  * @todo This should be done via an Authenticator object.
  */
 public function run(RequestInterface $request, ResponseInterface $response)
 {
     $username = $request->getParam('username');
     if (!$username) {
         $this->addFeedback('error', 'Missing username.');
         $this->setSuccess(false);
         return $response->withStatus(404);
     }
     $recaptchaValue = $request->getParam('g-recaptcha-response');
     if (!$recaptchaValue) {
         $this->addFeedback('error', 'Missing captcha.');
         $this->setSuccess(false);
         return $response->withStatus(404);
     }
     if (!$this->validateCaptcha($recaptchaValue)) {
         $this->addFeedback('error', 'Invalid captcha.');
         $this->setSuccess(false);
         return $response->withStatus(404);
     }
     $user = $this->loadUser($username);
     if (!$user) {
         // Fail silently.
         $this->logger->error('Lost password request: can not find user in database.');
         return $response;
     }
     $token = $this->generateLostPasswordToken($user);
     $this->sendLostPasswordEmail($user, $token);
     return $response;
 }
 /**
  * @param \Psr\Http\Message\RequestInterface $request
  *
  * @return \Psr\Http\Message\RequestInterface
  */
 public function sign(RequestInterface $request)
 {
     $timestamp = (new \DateTime('now', new \DateTimeZone('UTC')))->getTimestamp();
     $data = implode('|', [$request->getMethod(), rtrim((string) $request->getUri(), '/'), $timestamp]);
     $signature = $this->signer->sign($data);
     return $request->withHeader(self::TIMESTAMP_HEADER, $timestamp)->withHeader(self::SIGNATURE_HEADER, $signature);
 }
Example #10
0
 /**
  * Invoke this state. States are invoked until they return something
  * non-invokable.
  *
  * @param array $arguments All matched URL parameters.
  * @param Psr\Http\Message\RequestInterface $request The current request.
  * @return mixed Whatever the state eventually resolves to.
  */
 public function __invoke(array $arguments, RequestInterface $request)
 {
     $method = $request->getMethod();
     if (!isset($this->actions[$method])) {
         return new EmptyResponse(405);
     }
     $call = $this->actions[$method];
     $this->request = $request;
     do {
         $args = $this->parseArguments($call, $arguments);
         foreach ($args as &$value) {
             if (is_string($value) && $this->isHttpAction(substr($value, 1))) {
                 $key = substr($value, 1);
                 if ($key == $method) {
                     throw new EndlessStateLoopException();
                 }
                 if (isset($this->actions[$key])) {
                     $value = $this->actions[$key];
                 } else {
                     $value = new EmptyResponse(405);
                 }
             }
         }
         $call = call_user_func_array($call, $args);
     } while (is_callable($call));
     return $call;
 }
 function it_returns_body_with_headers(RequestInterface $request, Stream $stream)
 {
     $request->getHeaders()->shouldBeCalled()->willReturn(['content-type' => 'application/json']);
     $request->getBody()->shouldBeCalled()->willReturn($stream);
     $stream->getContents()->shouldBeCalled()->willReturn('{"data": {}}');
     $this->getBodyWithHeaders($request)->shouldReturn('content-type: application/json' . PHP_EOL . PHP_EOL . '{"data": {}}');
 }
Example #12
0
 /**
  * {@inheritdoc}
  */
 public function send(RequestInterface $request, array $options = array())
 {
     $options += Client::$defaultOptions;
     $curlOptions = $options['curl'] + array(CURLOPT_URL => (string) $request->getUri(), CURLOPT_CUSTOMREQUEST => $request->getMethod(), CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_HTTPHEADER => \EasyRequest\get_headers($request), CURLOPT_ENCODING => $request->getHeaderLine('Accept-Encoding'), CURLOPT_NOBODY => $options['nobody'], CURLOPT_CONNECTTIMEOUT => $options['timeout'], CURLOPT_HTTP_VERSION => $request->getProtocolVersion() == '1.0' ? CURL_HTTP_VERSION_1_0 : CURL_HTTP_VERSION_1_1);
     if ($options['upload']) {
         $body = $request->getBody();
         $curlOptions += array(CURLOPT_UPLOAD => true, CURLOPT_READFUNCTION => function ($ch, $fp, $length) use($body) {
             return $body->read($length);
         });
     } elseif ($options['body']) {
         $curlOptions[CURLOPT_POSTFIELDS] = (string) $request->getBody();
     }
     if ($options['proxy']) {
         $curlOptions += array(CURLOPT_PROXY => $options['proxy'], CURLOPT_PROXYTYPE => $options['proxy_type']);
         if ($options['proxy_userpwd']) {
             $curlOptions[CURLOPT_PROXYUSERPWD] = $options['proxy_userpwd'];
         }
     }
     if ($options['bindto']) {
         $curlOptions[CURLOPT_INTERFACE] = $options['bindto'];
     }
     $header = $body = '';
     $curlOptions[CURLOPT_HEADERFUNCTION] = $this->handleResponseHeader($header);
     $ch = curl_init();
     curl_setopt_array($ch, $curlOptions);
     $result = curl_exec($ch);
     curl_close($ch);
     if ($result === false) {
         throw new Exception(sprintf('%d - %s', curl_errno($ch), curl_error($ch)));
     }
     $body = substr($result, strlen($header));
     return Response::parse($header, $body);
 }
Example #13
0
 /**
  * Always add a x-amz-content-sha-256 for data integrity.
  */
 public function presign(RequestInterface $request, CredentialsInterface $credentials, $expires)
 {
     if (!$request->hasHeader('x-amz-content-sha256')) {
         $request = $request->withHeader('X-Amz-Content-Sha256', $this->getPresignedPayload($request));
     }
     return parent::presign($request, $credentials, $expires);
 }
Example #14
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);
     }
 }
Example #15
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);
 }
 /**
  * @return string|null
  */
 public function getLastRequestPath()
 {
     if (is_null($this->lastRequest)) {
         return null;
     }
     return $this->lastRequest->getUri();
 }
Example #17
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;
 }
 /**
  * @return string
  */
 public function getRequestId()
 {
     if ($this->request->hasHeader($this->headerName)) {
         return $this->request->getHeader($this->headerName);
     }
     return $this->fallback->getRequestId();
 }
Example #19
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());
 }
Example #20
0
 /**
  * @param RequestInterface $request
  * @return Message
  */
 public function convertRequestToMessage(RequestInterface $request)
 {
     parse_str($request->getBody(), $body);
     $message = new Message($body['Message-Id']);
     $message->setSubject($body['Subject']);
     if (!empty($body['Reply-To'])) {
         $message->setReplyTo($body['Reply-To']);
     } elseif (!empty($body['Reply-to'])) {
         $message->setReplyTo($body['Reply-to']);
     } elseif (!empty($body['reply-to'])) {
         $message->setReplyTo($body['reply-to']);
     }
     if (!empty($body['From'])) {
         $message->setFrom($body['From']);
     } else {
         $message->setFrom($body['from']);
     }
     if (isset($body['To'])) {
         $message->setTo($body['To']);
     }
     if (!empty($body['body-html'])) {
         $message->setBodyHtml($body['body-html']);
     }
     if (!empty($body['stripped-html'])) {
         $body['stripped-html'] = html_entity_decode($body['stripped-html']);
         if (strpos($body['stripped-html'], 'ĂĄ') !== false && stripos($body['stripped-html'], 'charset=iso-8859-2')) {
             $body['stripped-html'] = iconv('UTF-8', 'ISO-8859-2//TRANSLIT', $body['stripped-html']);
         } elseif (strpos($body['stripped-html'], 'á') !== false && stripos($body['stripped-html'], 'charset=windows-1250')) {
             $body['stripped-html'] = iconv('UTF-8', 'CP1250//TRANSLIT', $body['stripped-html']);
         }
         $message->setStrippedHtml($body['stripped-html']);
     }
     if (!empty($body['body-plain'])) {
         if (isset($body['stripped-html'])) {
             if (strpos($body['body-plain'], 'ĂĄ') !== false && stripos($body['stripped-html'], 'charset=iso-8859-2')) {
                 $body['body-plain'] = iconv('UTF-8', 'ISO-8859-2//TRANSLIT', $body['body-plain']);
             } elseif (strpos($body['body-plain'], 'á') !== false && stripos($body['stripped-html'], 'charset=windows-1250')) {
                 $body['body-plain'] = iconv('UTF-8', 'CP1250//TRANSLIT', $body['body-plain']);
             }
         }
         $message->setBodyPlain($body['body-plain']);
     }
     if (!empty($body['References'])) {
         $message->setReferences($body['References']);
     }
     $message->setDate((new \DateTime())->setTimestamp($body['timestamp']));
     $message->setSpam(isset($body['X-Mailgun-Sflag']) && $body['X-Mailgun-Sflag'] === 'yes');
     $message->setSpamScore(isset($body['X-Mailgun-Sscore']) ? (double) $body['X-Mailgun-Sscore'] : 0);
     if (isset($body['attachments'])) {
         foreach (json_decode($body['attachments']) as $at) {
             if ($at->name == 'smime.p7s') {
                 continue;
             }
             $attachment = new Attachment();
             $attachment->setName($at->name)->setUrl(str_replace('https://', 'https://*****:*****@', $at->url));
             $message->addAttachment($attachment);
         }
     }
     return $message;
 }
Example #21
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);
     }
 }
Example #22
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);
 }
 /**
  * @param RequestInterface  $request  A PSR-7 compatible Request instance.
  * @param ResponseInterface $response A PSR-7 compatible Response instance.
  * @return ResponseInterface
  */
 public function run(RequestInterface $request, ResponseInterface $response)
 {
     try {
         $objType = $request->getParam('obj_type');
         $objId = $request->getParam('obj_id');
         if (!$objType) {
             $this->setSuccess(false);
             return $response->withStatus(404);
         }
         if (!$objId) {
             $this->setSuccess(false);
             return $response->withStatus(404);
         }
         $this->logger->debug(sprintf('Admin Deleting object "%s" ID %s', $objType, $objId));
         $obj = $this->modelFactory()->create($objType);
         $obj->load($objId);
         if (!$obj->id()) {
             $this->setSuccess(false);
             return $response->withStatus(404);
         }
         $res = $obj->delete();
         if ($res) {
             $this->setSuccess(true);
             return $response;
         }
     } catch (Exception $e) {
         $this->setSuccess(false);
         return $response->withStatus(500);
     }
 }
Example #24
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);
 }
Example #25
0
 /**
  * Retrieves the HTTP protocol version as a string.
  *
  * The string MUST contain only the HTTP version number (e.g., "1.1", "1.0").
  *
  * @return string HTTP protocol version.
  */
 public function getProtocolVersion()
 {
     if ($this->overRidingProtocol !== null) {
         return $this->overRidingProtocol;
     }
     return $this->request->getProtocolVersion();
 }
Example #26
0
 private function addExpectHeader(RequestInterface $request, array $options, array &$modify)
 {
     // Determine if the Expect header should be used
     if ($request->hasHeader('Expect')) {
         return;
     }
     $expect = isset($options['expect']) ? $options['expect'] : null;
     // Return if disabled or if you're not using HTTP/1.1 or HTTP/2.0
     if ($expect === false || $request->getProtocolVersion() < 1.1) {
         return;
     }
     // The expect header is unconditionally enabled
     if ($expect === true) {
         $modify['set_headers']['Expect'] = '100-Continue';
         return;
     }
     // By default, send the expect header when the payload is > 1mb
     if ($expect === null) {
         $expect = 1048576;
     }
     // Always add if the body cannot be rewound, the size cannot be
     // determined, or the size is greater than the cutoff threshold
     $body = $request->getBody();
     $size = $body->getSize();
     if ($size === null || $size >= (int) $expect || !$body->isSeekable()) {
         $modify['set_headers']['Expect'] = '100-Continue';
     }
 }
Example #27
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;
 }
 /**
  * 通过提供的凭证,对特定请求进行签名,并添加对应的 HTTP 头至请求中。
  *
  * @param RequestInterface     $request    要签名的请求。
  * @param CredentialsInterface $credential 使用的凭证。
  *
  * @return RequestInterface 修改(签名)过的请求。
  */
 public function signRequest(RequestInterface $request, CredentialsInterface $credential)
 {
     $content = base64_encode($credential['key'] . ':' . $credential['secret']);
     $basicSignature = "Basic {$content}";
     // 先清除之前可能存在的 HTTP 头。
     return $request->withoutHeader('Authorization')->withHeader('Authorization', $basicSignature);
 }
 public function render(RequestInterface $request, ResponseInterface $response, $data)
 {
     $mediaType = $this->determineMediaType($request->getHeaderLine('Accept'));
     $output = $this->renderOutput($mediaType, $data);
     $response = $this->writeBody($response, $output);
     $response = $response->withHeader('Content-type', $mediaType);
     return $response;
 }
Example #30
-15
 /**
  * {@inheritdoc}
  */
 public function authenticate(RequestInterface $request)
 {
     // TODO: add error handling
     // TODO: support other grant types?
     $accessToken = $this->provider->getAccessToken('client_credentials');
     return $request->withHeader('Authorization', 'Bearer ' . $accessToken);
 }