RequestInterface PHP Class Code Examples

This page contains top rated real world PHP examples of class RequestInterface extracted from open source projects. You can rate examples to help us improve the quality of examples

Example #1
Show file File: S3Signature.php Project: nstanard/webpagetest
1
 /**
  * Create a canonicalized resource for a request
  *
  * @param RequestInterface $request Request for the resource
  *
  * @return string
  */
 private function createCanonicalizedResource(RequestInterface $request)
 {
     $buffer = $request->getParams()->get('s3.resource');
     // When sending a raw HTTP request (e.g. $client->get())
     if (null === $buffer) {
         $bucket = $request->getParams()->get('bucket') ?: $this->parseBucketName($request);
         // Use any specified bucket name, the parsed bucket name, or no bucket name when interacting with GetService
         $buffer = $bucket ? "/{$bucket}" : '';
         // Remove encoding from the path and use the S3 specific encoding
         $path = S3Client::encodeKey(rawurldecode($request->getPath()));
         // if the bucket was path style, then ensure that the bucket wasn't duplicated in the resource
         $buffer .= preg_replace("#^/{$bucket}/{$bucket}#", "/{$bucket}", $path);
     }
     // Remove double slashes
     $buffer = str_replace('//', '/', $buffer);
     // Add sub resource parameters
     $query = $request->getQuery();
     $first = true;
     foreach ($this->signableQueryString as $key) {
         if ($query->hasKey($key)) {
             $value = $query[$key];
             $buffer .= $first ? '?' : '&';
             $first = false;
             $buffer .= $key;
             // Don't add values for empty sub-resources
             if ($value !== '' && $value !== false && $value !== null && $value !== QueryString::BLANK) {
                 $buffer .= "={$value}";
             }
         }
     }
     return $buffer;
 }
Example #2
Show file File: RedirectPlugin.php Project: mickdane/zidisha
0
 /**
  * Send a redirect request and handle any errors
  *
  * @param RequestInterface $original The originating request
  * @param RequestInterface $request  The current request being redirected
  * @param Response         $response The response of the current request
  *
  * @throws BadResponseException|\Exception
  */
 protected function sendRedirectRequest(RequestInterface $original, RequestInterface $request, Response $response)
 {
     // Validate and create a redirect request based on the original request and current response
     if ($redirectRequest = $this->prepareRedirection($original, $request, $response)) {
         try {
             $redirectRequest->send();
         } catch (BadResponseException $e) {
             $e->getResponse();
             if (!$e->getResponse()) {
                 throw $e;
             }
         }
     }
 }
Example #3
Show file File: FBSGuzzleHttpClient.php Project: AnnaCaraman/ding2
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;
 }
Example #4
Show file File: S3Client.php Project: iLoiLohas/pinchshopper
0
 /**
  * Create a pre-signed URL for a request
  *
  * @param RequestInterface     $request Request to generate the URL for. Use the factory methods of the client to
  *                                      create this request object
  * @param int|string|\DateTime $expires The time at which the URL should expire. This can be a Unix timestamp, a
  *                                      PHP DateTime object, or a string that can be evaluated by strtotime
  *
  * @return string
  * @throws InvalidArgumentException if the request is not associated with this client object
  */
 public function createPresignedUrl(RequestInterface $request, $expires)
 {
     if ($request->getClient() !== $this) {
         throw new InvalidArgumentException('The request object must be associated with the client. Use the ' . '$client->get(), $client->head(), $client->post(), $client->put(), etc. methods when passing in a ' . 'request object');
     }
     return $this->signature->createPresignedUrl($request, $this->credentials, $expires);
 }
Example #5
Show file File: AssetManager.php Project: jguittard/AssetManager
0
 /**
  * Check if the request resolves to an asset.
  *
  * @param    RequestInterface $request
  * @return   boolean
  */
 public function resolvesToAsset(RequestInterface $request)
 {
     if (null === $this->asset) {
         $this->asset = $this->resolve($request);
     }
     return (bool) $this->asset;
 }
Example #6
Show file File: MockPlugin.php Project: creazy412/vmware-win10-c65-drupal7
0
 /**
  * Get a response from the front of the list and add it to a request
  *
  * @param RequestInterface $request Request to mock
  *
  * @return self
  * @throws CurlException When request.send is called and an exception is queued
  */
 public function dequeue(RequestInterface $request)
 {
     $this->dispatch('mock.request', array('plugin' => $this, 'request' => $request));
     $item = array_shift($this->queue);
     if ($item instanceof Response) {
         if ($this->readBodies && $request instanceof EntityEnclosingRequestInterface) {
             $request->getEventDispatcher()->addListener('request.sent', $f = function (Event $event) use(&$f) {
                 while ($data = $event['request']->getBody()->read(8096)) {
                 }
                 // Remove the listener after one-time use
                 $event['request']->getEventDispatcher()->removeListener('request.sent', $f);
             });
         }
         $request->setResponse($item);
     } elseif ($item instanceof CurlException) {
         // Emulates exceptions encountered while transferring requests
         $item->setRequest($request);
         $request->setState(RequestInterface::STATE_ERROR);
         $request->dispatch('request.exception', array('request' => $request, 'exception' => $item));
         // Only throw if the exception wasn't handled
         if ($request->getState() == RequestInterface::STATE_ERROR) {
             throw $item;
         }
     }
     return $this;
 }
Example #7
Show file File: RFC6455.php Project: unkerror/Budabot
0
 /**
  * {@inheritdoc}
  */
 public function handshake(RequestInterface $request)
 {
     if (true !== $this->_verifier->verifyAll($request)) {
         return new Response(400);
     }
     return new Response(101, array('Upgrade' => 'websocket', 'Connection' => 'Upgrade', 'Sec-WebSocket-Accept' => $this->sign($request->getHeader('Sec-WebSocket-Key'))));
 }
Example #8
Show file File: CachePlugin.php Project: diandianxiyu/Yii2Api
0
 /**
  * Check if a cache response satisfies a request's caching constraints
  *
  * @param RequestInterface $request  Request to validate
  * @param Response         $response Response to validate
  *
  * @return bool
  */
 public function canResponseSatisfyRequest(RequestInterface $request, Response $response)
 {
     $responseAge = $response->calculateAge();
     $reqc = $request->getHeader('Cache-Control');
     $resc = $response->getHeader('Cache-Control');
     // Check the request's max-age header against the age of the response
     if ($reqc && $reqc->hasDirective('max-age') && $responseAge > $reqc->getDirective('max-age')) {
         return false;
     }
     // Check the response's max-age header
     if ($response->isFresh() === false) {
         $maxStale = $reqc ? $reqc->getDirective('max-stale') : null;
         if (null !== $maxStale) {
             if ($maxStale !== true && $response->getFreshness() < -1 * $maxStale) {
                 return false;
             }
         } elseif ($resc && $resc->hasDirective('max-age') && $responseAge > $resc->getDirective('max-age')) {
             return false;
         }
     }
     if ($this->revalidation->shouldRevalidate($request, $response)) {
         try {
             return $this->revalidation->revalidate($request, $response);
         } catch (CurlException $e) {
             $request->getParams()->set('cache.hit', 'error');
             return $this->canResponseSatisfyFailedRequest($request, $response);
         }
     }
     return true;
 }
Example #9
Show file File: Customer.php Project: pradeep-wagento/magento2
0
 /**
  * Check customer authentication for some actions
  *
  * @param \Magento\Framework\App\RequestInterface $request
  * @return \Magento\Framework\App\ResponseInterface
  */
 public function dispatch(RequestInterface $request)
 {
     if (!$this->customerSession->authenticate()) {
         $this->_actionFlag->set('', self::FLAG_NO_DISPATCH, true);
     }
     return parent::dispatch($request);
 }
Example #10
Show file File: Address.php Project: kidaa30/magento2-platformsh
0
 /**
  * Check customer authentication
  *
  * @param RequestInterface $request
  * @return \Magento\Framework\App\ResponseInterface
  */
 public function dispatch(RequestInterface $request)
 {
     if (!$this->_getSession()->authenticate()) {
         $this->_actionFlag->set('', 'no-dispatch', true);
     }
     return parent::dispatch($request);
 }
Example #11
Show file File: StepMiddleware.php Project: blackfireio/player
0
 private function prepareRequest(Step $step, ValueBag $values, RequestInterface $request, $options)
 {
     $options['allow_redirects'] = false;
     if (!$step->getDelay()) {
         $options['delay'] = 0;
     } else {
         try {
             $options['delay'] = $this->language->evaluate($step->getDelay(), $values->all(true));
         } catch (ExpressionSyntaxError $e) {
             $msg = sprintf('Delay syntax error in "%s": %s', $step->getDelay(), $e->getMessage());
             $this->logger and $this->logger->critical($msg, ['request' => $request->getHeaderLine('X-Request-Id')]);
             throw new InvalidArgumentException($msg);
         }
     }
     unset($options['expectations']);
     if ($step->getExpectations()) {
         $options['expectations'] = $step->getExpectations();
     }
     unset($options['extractions']);
     if ($step->getExtractions()) {
         $options['extractions'] = $step->getExtractions();
     }
     foreach ($this->extensions as $extension) {
         $options = $extension->prepareRequest($step, $values, $request, $options);
     }
     return $options;
 }
Example #12
Show file File: Index.php Project: kidaa30/magento2-platformsh
0
 /**
  * Dispatch request
  *
  * @param RequestInterface $request
  * @return \Magento\Framework\App\ResponseInterface
  * @throws \Magento\Framework\Exception\NotFoundException
  */
 public function dispatch(RequestInterface $request)
 {
     if (!$this->scopeConfig->isSetFlag(self::XML_PATH_ENABLED, ScopeInterface::SCOPE_STORE)) {
         throw new NotFoundException(__('Page not found.'));
     }
     return parent::dispatch($request);
 }
Example #13
Show file File: S3Signature.php Project: ebeauchamps/brilliantretail
0
 /**
  * Create a canonicalized resource for a request
  *
  * @param RequestInterface $request Request for the resource
  *
  * @return string
  */
 protected function createCanonicalizedResource(RequestInterface $request)
 {
     $buffer = $request->getParams()->get('s3.resource');
     // When sending a raw HTTP request (e.g. $client->get())
     if (null === $buffer) {
         $bucket = $request->getParams()->get('bucket') ?: $this->parseBucketName($request);
         // Use any specified bucket name, the parsed bucket name, or no bucket name when interacting with GetService
         $buffer = $bucket ? "/{$bucket}" : '';
         // Remove encoding from the path and use the S3 specific encoding
         $path = S3Client::encodeKey(rawurldecode($request->getPath()));
         // if the bucket was path style, then ensure that the bucket wasn't duplicated in the resource
         $buffer .= preg_replace("#^/{$bucket}/{$bucket}#", "/{$bucket}", $path);
     }
     // Remove double slashes
     $buffer = str_replace('//', '/', $buffer);
     // Add sub resource parameters
     $query = $request->getQuery();
     $first = true;
     foreach ($this->signableQueryString as $key) {
         if ($value = $query->get($key)) {
             $buffer .= $first ? '?' : '&';
             $first = false;
             $buffer .= $key;
             if ($value !== QueryString::BLANK) {
                 $buffer .= "={$value}";
             }
         }
     }
     return $buffer;
 }
Example #14
Show file File: MessageFactory.php Project: hilmysyarif/sic
0
 private function add_events(RequestInterface $request, $value)
 {
     if (!is_array($value)) {
         throw new \InvalidArgumentException('events value must be an array');
     }
     $this->attachListeners($request, $this->prepareListeners($value, ['before', 'complete', 'error', 'headers']));
 }
Example #15
Show file File: S3Client.php Project: kissingwolf/namedmanager
0
 /**
  * Create a pre-signed URL for a request
  *
  * @param RequestInterface     $request Request to generate the URL for. Use the factory methods of the client to
  *                                      create this request object
  * @param int|string|\DateTime $expires The time at which the URL should expire. This can be a Unix timestamp, a
  *                                      PHP DateTime object, or a string that can be evaluated by strtotime
  *
  * @return string
  * @throws InvalidArgumentException if the request is not associated with this client object
  */
 public function createPresignedUrl(RequestInterface $request, $expires)
 {
     if ($request->getClient() !== $this) {
         throw new InvalidArgumentException('The request object must be associated with the client. Use the ' . '$client->get(), $client->head(), $client->post(), $client->put(), etc. methods when passing in a ' . 'request object');
     }
     if ($expires instanceof \DateTime) {
         $expires = $expires->getTimestamp();
     } elseif (!is_numeric($expires)) {
         $expires = strtotime($expires);
     }
     // Operate on a clone of the request, so the original is not altered
     $request = clone $request;
     // URL encoding already occurs in the URI template expansion. Undo that and encode using the same encoding as
     // GET object, PUT object, etc.
     $path = $this->encodeKey(rawurldecode($request->getPath()));
     $request->setPath($path);
     // Make sure to handle temporary credentials
     if ($token = $this->credentials->getSecurityToken()) {
         $request->setHeader('x-amz-security-token', $token);
         $request->getQuery()->set('x-amz-security-token', $token);
     }
     // Set query params required for pre-signed URLs
     $request->getQuery()->set('AWSAccessKeyId', $this->credentials->getAccessKeyId())->set('Expires', $expires)->set('Signature', $this->signature->signString($this->signature->createCanonicalizedString($request, $expires), $this->credentials));
     return $request->getUrl();
 }
Example #16
Show file File: AbstractConfig.php Project: pradeep-wagento/magento2
0
 /**
  * Check if current section is found and is allowed
  *
  * @param \Magento\Framework\App\RequestInterface $request
  * @return \Magento\Framework\App\ResponseInterface
  */
 public function dispatch(\Magento\Framework\App\RequestInterface $request)
 {
     if (!$request->getParam('section')) {
         $request->setParam('section', $this->_configStructure->getFirstSection()->getId());
     }
     return parent::dispatch($request);
 }
Example #17
Show file File: RequestFactory.php Project: stof/player
0
 private function createRequestFromFollow(Step $step, ValueBag $values, RequestInterface $request = null, ResponseInterface $response = null, Crawler $crawler = null)
 {
     if (null === $request || null === $response) {
         throw new CrawlException('Unable to follow when no previous page.');
     }
     if ('3' !== substr($response->getStatusCode(), 0, 1) || !$response->hasHeader('Location')) {
         throw new CrawlException('Unable to follow when no previous page is not a redirect.');
     }
     // logic from Guzzle\RedirectMiddleware
     // Request modifications to apply.
     $modify = [];
     // Use a GET request if this is an entity enclosing request and we are
     // not forcing RFC compliance, but rather emulating what all browsers
     // would do.
     $statusCode = $response->getStatusCode();
     if ($statusCode == 303 || $statusCode <= 302 && $request->getBody()) {
         $modify['method'] = 'GET';
         $modify['body'] = '';
     }
     $modify['uri'] = Psr7\Uri::resolve($request->getUri(), $response->getHeaderLine('Location'));
     Psr7\rewind_body($request);
     // Add the Referer header only if we are not redirecting from https to http
     if ($modify['uri']->getScheme() === $request->getUri()->getScheme()) {
         $modify['set_headers']['Referer'] = (string) $request->getUri()->withUserInfo('', '');
     } else {
         $modify['remove_headers'][] = 'Referer';
     }
     // Remove Authorization header if host is different
     if ($request->getUri()->getHost() !== $modify['uri']->getHost()) {
         $modify['remove_headers'][] = 'Authorization';
     }
     return Psr7\modify_request($request, $modify);
 }
Example #18
Show file File: BackendAuthentication.php Project: kidaa30/magento2-platformsh
0
 /**
  * Replace standard admin login form with HTTP Basic authentication
  *
  * @param AbstractAction $subject
  * @param callable $proceed
  * @param RequestInterface $request
  * @return ResponseInterface
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function aroundDispatch(AbstractAction $subject, \Closure $proceed, RequestInterface $request)
 {
     $resource = isset($this->aclResources[$request->getControllerName()]) ? isset($this->aclResources[$request->getControllerName()][$request->getActionName()]) ? $this->aclResources[$request->getControllerName()][$request->getActionName()] : $this->aclResources[$request->getControllerName()] : null;
     $type = $request->getParam('type');
     $resourceType = isset($this->aclResources[$type]) ? $this->aclResources[$type] : null;
     if (!$resource || !$resourceType) {
         return parent::aroundDispatch($subject, $proceed, $request);
     }
     $session = $this->_auth->getAuthStorage();
     // Try to login using HTTP-authentication
     if (!$session->isLoggedIn()) {
         list($login, $password) = $this->httpAuthentication->getCredentials();
         try {
             $this->_auth->login($login, $password);
         } catch (AuthenticationException $e) {
             $this->logger->critical($e);
         }
     }
     // Verify if logged in and authorized
     if (!$session->isLoggedIn() || !$this->authorization->isAllowed($resource) || !$this->authorization->isAllowed($resourceType)) {
         $this->httpAuthentication->setAuthenticationFailed('RSS Feeds');
         return $this->_response;
     }
     return parent::aroundDispatch($subject, $proceed, $request);
 }
Example #19
Show file File: Address.php Project: pradeep-wagento/magento2
0
 /**
  * {@inheritdoc}
  */
 public function dispatch(\Magento\Framework\App\RequestInterface $request)
 {
     if (!$this->_getCheckout()->getCustomer()->getId()) {
         return $this->_redirect('customer/account/login');
     }
     return parent::dispatch($request);
 }
Example #20
Show file File: Redirect.php Project: kadivar/sentora-whmcs
0
 private function modifyRedirectRequest(RequestInterface $request, ResponseInterface $response)
 {
     $config = $request->getConfig();
     $protocols = $config->getPath('redirect/protocols') ?: array('http', 'https');
     // Use a GET request if this is an entity enclosing request and we are
     // not forcing RFC compliance, but rather emulating what all browsers
     // would do.
     $statusCode = $response->getStatusCode();
     if ($statusCode == 303 || $statusCode <= 302 && $request->getBody() && !$config->getPath('redirect/strict')) {
         $request->setMethod('GET');
         $request->setBody(null);
     }
     $previousUrl = $request->getUrl();
     $this->setRedirectUrl($request, $response, $protocols);
     $this->rewindEntityBody($request);
     // Add the Referer header if it is told to do so and only
     // add the header if we are not redirecting from https to http.
     if ($config->getPath('redirect/referer') && ($request->getScheme() == 'https' || $request->getScheme() == $config['redirect_scheme'])) {
         $url = Url::fromString($previousUrl);
         $url->setUsername(null);
         $url->setPassword(null);
         $request->setHeader('Referer', (string) $url);
     } else {
         $request->removeHeader('Referer');
     }
 }
Example #21
Show file File: ServerRequest.php Project: bweston92/expressive-async
0
 /**
  * @param RequestInterface $request
  */
 public function __construct(RequestInterface $request = null)
 {
     if (is_null($request)) {
         $request = new Request();
     }
     $this->request = $request;
 }
Example #22
Show file File: TokenController.php Project: hoaquynhtim99/nukeviet-oauth2
0
 public function handleRevokeRequest(RequestInterface $request, ResponseInterface $response)
 {
     if ($this->revokeToken($request, $response)) {
         $response->setStatusCode(200);
         $response->addParameters(array('revoked' => true));
     }
 }