protected function getNotFoundResponse(RequestInterface $request, ResponseInterface $response, \Exception $exception)
 {
     $output = json_encode(['error_message' => $exception->getMessage()], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
     $body = new Body(fopen('php://temp', 'r+'));
     $body->write($output);
     return $response->withStatus(404)->withHeader('Content-type', 'application/json')->withBody($body);
 }
 /**
  * Check the response status code.
  *
  * @param ResponseInterface $response
  * @param int $expectedStatusCode
  *
  * @throws \RuntimeException on unexpected status code
  */
 private function checkResponseStatusCode(ResponseInterface $response, $expectedStatusCode)
 {
     $statusCode = $response->getStatusCode();
     if ($statusCode !== $expectedStatusCode) {
         throw new \RuntimeException('Wunderlist API returned status code ' . $statusCode . ' expected ' . $expectedStatusCode);
     }
 }
Example #3
0
 /**
  * Checks Fitbit API response for errors.
  *
  * @throws IdentityProviderException
  * @param  ResponseInterface $response
  * @param  array|string $data Parsed response data
  * @return void
  */
 protected function checkResponse(ResponseInterface $response, $data)
 {
     if (!empty($data['errors'][0])) {
         $message = $data['errors'][0]['errorType'] . ': ' . $data['errors'][0]['message'];
         throw new IdentityProviderException($message, $response->getStatusCode(), $data);
     }
 }
 /**
  * @param ServerRequestInterface $request the current request
  * @param ResponseInterface $response
  * @return ResponseInterface the response with the content
  */
 public function mainAction(ServerRequestInterface $request, ResponseInterface $response)
 {
     $this->initPage();
     $this->main();
     $response->getBody()->write($this->content);
     return $response;
 }
 protected function payload(ResponseInterface $response, StructureShape $member, array &$result)
 {
     $jsonBody = $this->parseJson($response->getBody());
     if ($jsonBody) {
         $result += $this->parser->parse($member, $jsonBody);
     }
 }
Example #6
0
 /**
  * Invoke error handler
  *
  * @param  ServerRequestInterface $request  The most recent Request object
  * @param  ResponseInterface      $response The most recent Response object
  * @param  string[]               $methods  Allowed HTTP methods
  *
  * @return ResponseInterface
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, array $methods)
 {
     if ($request->getMethod() === 'OPTIONS') {
         $status = 200;
         $contentType = 'text/plain';
         $output = $this->renderPlainNotAllowedMessage($methods);
     } else {
         $status = 405;
         $contentType = $this->determineContentType($request);
         switch ($contentType) {
             case 'application/json':
                 $output = $this->renderJsonNotAllowedMessage($methods);
                 break;
             case 'text/xml':
             case 'application/xml':
                 $output = $this->renderXmlNotAllowedMessage($methods);
                 break;
             case 'text/html':
                 $output = $this->renderHtmlNotAllowedMessage($methods);
                 break;
         }
     }
     $body = new Body(fopen('php://temp', 'r+'));
     $body->write($output);
     $allow = implode(', ', $methods);
     return $response->withStatus($status)->withHeader('Content-type', $contentType)->withHeader('Allow', $allow)->withBody($body);
 }
Example #7
0
 /**
  * @param \Psr\Http\Message\ResponseInterface $response
  * @throws \Exception
  */
 public function validateBody(ResponseInterface $response)
 {
     $errors = $this->validateMessage(json_decode($response->getBody()));
     if (empty($errors) === false) {
         $this->exceptionFactory->createResponseBodyInvalidJsonApiException($response, $errors, $this->includeOriginalMessage);
     }
 }
 /**
  * Return a new exception depending on the HTTP status code
  *
  * @param ResponseInterface $response Server-side response
  * @return ActionAlreadyDoneException|BadRequestException|BadTokenException|PermissionDeniedException|RealDebridException|UnknownResourceException
  */
 public static function create(ResponseInterface $response)
 {
     $error = json_decode($response->getBody());
     switch ($response->getStatusCode()) {
         case 202:
             return new ActionAlreadyDoneException();
             break;
             /*case 400:
               return new BadRequestException();
               break;*/
         /*case 400:
           return new BadRequestException();
           break;*/
         case 401:
             return new BadTokenException();
             break;
         case 403:
             return new PermissionDeniedException();
             break;
         case 404:
             return new UnknownResourceException();
             break;
         case 503:
             return new FileUnavailableException();
             break;
     }
     return new RealDebridException($error);
 }
Example #9
0
 public function getErrorResponse(Response $response)
 {
     $stream = $response->getBody();
     if ($this->errorCode > 0) {
         $stream->write(json_encode($this->getError()));
     }
     switch ($this->errorCode) {
         case self::CODE_NULL:
             $response = $response->withStatus(200, 'Unknown');
             break;
         case self::CODE_GENERIC:
             $response = $response->withBody($stream)->withStatus(400, 'Invalid request');
             break;
         case self::CODE_DATA_MISSING:
         case self::CODE_DATA_INVALID:
         case self::CODE_DATA_EXIST:
             $response = $response->withBody($stream)->withStatus(400, 'Invalid request');
             break;
         case self::CODE_DATA_NOT_FOUND:
             $response = $response->withBody($stream)->withStatus(404, 'Not found');
             break;
         case self::CODE_DB_UPDATE_FAILED:
         case self::CODE_FATAL:
             $response = $response->withBody($stream)->withStatus(500, 'Server Error');
             break;
         default:
             $response = $response->withStatus(200, 'Unknown');
             break;
     }
     return $response;
 }
Example #10
0
 protected function checkResponse(ResponseInterface $response, $data)
 {
     if ($response->getStatusCode() >= 400) {
         $msg = $data['error_description'] ?: (string) $response->getReasonPhrase();
         throw new IdentityProviderException($msg, $response->getStatusCode(), $response);
     }
 }
Example #11
0
 /**
  * Helper method responsible for constructing and returning {@see BadResponseError} exceptions.
  *
  * @param RequestInterface  $request  The faulty request
  * @param ResponseInterface $response The error-filled response
  *
  * @return BadResponseError
  */
 public function httpError(RequestInterface $request, ResponseInterface $response)
 {
     $message = $this->header('HTTP Error');
     $message .= sprintf("The remote server returned a \"%d %s\" error for the following transaction:\n\n", $response->getStatusCode(), $response->getReasonPhrase());
     $message .= $this->header('Request');
     $message .= trim(str($request)) . PHP_EOL . PHP_EOL;
     $message .= $this->header('Response');
     $message .= trim(str($response)) . PHP_EOL . PHP_EOL;
     $message .= $this->header('Further information');
     // @codeCoverageIgnoreStart
     switch ($response->getStatusCode()) {
         case 400:
             $message .= "Please ensure that your input values are valid and well-formed. ";
             break;
         case 401:
             $message .= "Please ensure that your authentication credentials are valid. ";
             break;
         case 404:
             $message .= "Please ensure that the resource you're trying to access actually exists. ";
             break;
         case 500:
             $message .= "Please try this operation again once you know the remote server is operational. ";
             break;
     }
     // @codeCoverageIgnoreEnd
     $message .= "Visit http://docs.php-opencloud.com/en/latest/http-codes for more information about debugging " . "HTTP status codes, or file a support issue on https://github.com/php-opencloud/openstack/issues.";
     $e = new BadResponseError($message);
     $e->setRequest($request);
     $e->setResponse($response);
     return $e;
 }
Example #12
0
 /**
  * Get status code of response.
  *
  * @return int
  * @throws ComicApiException
  */
 public function getStatusCode()
 {
     if ($this->response instanceof ResponseInterface) {
         return $this->response->getStatusCode();
     }
     throw new ComicApiException("You can't get response without making request.");
 }
Example #13
0
 /**
  * @param Request $request
  * @param Response $response
  * @param $args
  * @return Response
  */
 public function save(Request $request, Response $response, $args)
 {
     $id = trim($request->getHeader('id')[0]);
     $summary = trim($request->getHeader('summary')[0]);
     $description = trim($request->getHeader('description')[0]);
     $dueDate = trim($request->getHeader('dueDate')[0]);
     if (!$summary) {
         $response->withStatus(500);
     } else {
         try {
             /**
              * @var Ticket $ticket ;
              */
             $ticket = null;
             if ($id) {
                 $ticket = $this->em->find('App\\Entity\\Ticket', $id);
             } else {
                 $ticket = new Ticket();
             }
             $ticket->setSummary($summary);
             $ticket->setDescription($description);
             $ticket->setDueDate($dueDate ? date_create_from_format('j/m/Y', $dueDate) : null);
             $this->em->persist($ticket);
             $this->em->flush();
             $this->render($response, $ticket);
         } catch (\Exception $e) {
             $response->withStatus(500);
         }
     }
     return $response;
 }
 public function modify(ResponseInterface $response) : ResponseInterface
 {
     if (false === strpos($response->getHeaderLine('Content-Type'), 'application/json')) {
         return $response;
     }
     return $response->withHeader('Content-Type', $this->contentType);
 }
 /**
  * Handle an exception.
  *
  * Calls on prepareWhoopsHandler() to inject additional data tables into
  * the generated payload, and then injects the response with the result
  * of whoops handling the exception.
  *
  * @param \Exception $exception
  * @param Request $request
  * @param Response $response
  * @return Response
  */
 protected function handleException(\Exception $exception, Request $request, Response $response)
 {
     $this->prepareWhoopsHandler($request);
     $this->whoops->pushHandler($this->whoopsHandler);
     $response->getBody()->write($this->whoops->handleException($exception));
     return $response;
 }
Example #16
0
 private function handleError(ServerRequestInterface $request, ResponseInterface $response, Exception $exception)
 {
     $output = $this->renderJsonErrorMessage($exception);
     $body = new Body(fopen('php://temp', 'r+'));
     $body->write($output);
     return $response->withStatus(500)->withHeader('Content-type', 'application/json')->withBody($body);
 }
Example #17
0
 public function __invoke(Request $request, Response $response, PayloadInterface $payload = null) : Response
 {
     $file = $this->getTemplateFile();
     $html = $this->render($file, $payload->getOutput());
     $response->getBody()->write($html);
     return $response;
 }
 /**
  * Check a provider response for errors.
  *
  * @throws IdentityProviderException
  * @param  ResponseInterface $response
  * @param  string $data Parsed response data
  * @return void
  */
 protected function checkResponse(ResponseInterface $response, $data)
 {
     $statusCode = $response->getStatusCode();
     if ($statusCode >= 400) {
         throw new IdentityProviderException(isset($data['meta']['errorDetail']) ? $data['meta']['errorDetail'] : $response->getReasonPhrase(), $statusCode, $response);
     }
 }
Example #19
0
 /**
  * Returns the JS file content
  *
  * @param ContainerInterface $container Dependency injection container
  * @param ServerRequestInterface $request Request object
  * @param ResponseInterface $response Response object
  * @param array $args Associative list of route parameters
  * @return ResponseInterface $response Modified response object with generated output
  */
 public static function fileAction(ContainerInterface $container, ServerRequestInterface $request, ResponseInterface $response, array $args)
 {
     $contents = '';
     $files = array();
     $aimeos = $container->get('aimeos');
     $type = isset($args['type']) ? $args['type'] : 'js';
     foreach ($aimeos->getCustomPaths('admin/jqadm') as $base => $paths) {
         foreach ($paths as $path) {
             $jsbAbsPath = $base . '/' . $path;
             $jsb2 = new \Aimeos\MW\Jsb2\Standard($jsbAbsPath, dirname($jsbAbsPath));
             $files = array_merge($files, $jsb2->getFiles($type));
         }
     }
     foreach ($files as $file) {
         if (($content = file_get_contents($file)) !== false) {
             $contents .= $content;
         }
     }
     $response->getBody()->write($contents);
     if ($type === 'js') {
         $response = $response->withHeader('Content-Type', 'application/javascript');
     } elseif ($type === 'css') {
         $response = $response->withHeader('Content-Type', 'text/css');
     }
     return $response;
 }
Example #20
0
 /**
  * Execute the middleware.
  *
  * @param RequestInterface  $request
  * @param ResponseInterface $response
  * @param callable          $next
  *
  * @return ResponseInterface
  */
 public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
 {
     $key = $this->getCacheKey($request);
     $item = $this->cache->getItem($key);
     //If it's cached
     if ($item->isHit()) {
         $headers = $item->get();
         $cachedResponse = $response->withStatus(304);
         foreach ($headers as $name => $header) {
             $cachedResponse = $cachedResponse->withHeader($name, $header);
         }
         if ($this->cacheUtil->isNotModified($request, $cachedResponse)) {
             return $cachedResponse;
         }
         $this->cache->deleteItem($key);
     }
     $response = $next($request, $response);
     //Add cache-control header
     if ($this->cacheControl && !$response->hasHeader('Cache-Control')) {
         $response = $this->cacheUtil->withCacheControl($response, $this->cacheControl);
     }
     //Add Last-Modified header
     if (!$response->hasHeader('Last-Modified')) {
         $response = $this->cacheUtil->withLastModified($response, time());
     }
     //Save in the cache
     if ($this->cacheUtil->isCacheable($response)) {
         $item->set($response->getHeaders());
         $item->expiresAfter($this->cacheUtil->getLifetime($response));
         $this->cache->save($item);
     }
     return $response;
 }
Example #21
0
 /**
  * Sets the TYPO3 Backend context to a certain workspace,
  * called by the Backend toolbar menu
  *
  * @param ServerRequestInterface $request
  * @param ResponseInterface $response
  * @return ResponseInterface
  */
 public function switchWorkspaceAction(ServerRequestInterface $request, ResponseInterface $response)
 {
     $parsedBody = $request->getParsedBody();
     $queryParams = $request->getQueryParams();
     $workspaceId = (int) (isset($parsedBody['workspaceId']) ? $parsedBody['workspaceId'] : $queryParams['workspaceId']);
     $pageId = (int) (isset($parsedBody['pageId']) ? $parsedBody['pageId'] : $queryParams['pageId']);
     $finalPageUid = 0;
     $originalPageId = $pageId;
     $this->getBackendUser()->setWorkspace($workspaceId);
     while ($pageId) {
         $page = BackendUtility::getRecordWSOL('pages', $pageId, '*', ' AND pages.t3ver_wsid IN (0, ' . $workspaceId . ')');
         if ($page) {
             if ($this->getBackendUser()->doesUserHaveAccess($page, 1)) {
                 break;
             }
         } else {
             $page = BackendUtility::getRecord('pages', $pageId);
         }
         $pageId = $page['pid'];
     }
     if (isset($page['uid'])) {
         $finalPageUid = (int) $page['uid'];
     }
     $ajaxResponse = ['title' => \TYPO3\CMS\Workspaces\Service\WorkspaceService::getWorkspaceTitle($workspaceId), 'workspaceId' => $workspaceId, 'pageId' => $finalPageUid && $originalPageId == $finalPageUid ? null : $finalPageUid];
     $response->getBody()->write(json_encode($ajaxResponse));
     return $response;
 }
 public static function decode(ResponseInterface $response)
 {
     if ($response->hasHeader('Content-Type') && $response->getHeader('Content-Type')[0] == 'application/json') {
         return json_decode((string) $response->getBody(), true);
     }
     return (string) $response->getBody();
 }
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $out = null)
 {
     $page = intval($request->getAttribute('page')) ?: 0;
     $pictures = $this->apodApi->getPage($page, $this->resultsPerPage);
     $response->getBody()->write(json_encode($pictures));
     return $response->withHeader('Cache-Control', ['public', 'max-age=3600'])->withHeader('Content-Type', 'application/json');
 }
Example #24
0
 /**
  * Check a provider response for errors.
  *
  * @link https://developer.uber.com/v1/api-reference/
  * @throws IdentityProviderException
  * @param  ResponseInterface $response
  * @param  string $data Parsed response data
  * @return void
  */
 protected function checkResponse(ResponseInterface $response, $data)
 {
     $acceptableStatuses = [200, 201];
     if (!in_array($response->getStatusCode(), $acceptableStatuses)) {
         throw new IdentityProviderException($data['message'] ?: $response->getReasonPhrase(), $response->getStatusCode(), $response);
     }
 }
Example #25
0
 /**
  * Invoca la respuesta
  *
  * @param ServerRequestInterface $request  Instancia de ServerRequestInterface
  * @param ResponseInterface      $response Instancia de ResponseInterface
  * @param \Throwable             $error    Instancia de Throwable
  *
  * @return mixed
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, \Throwable $error)
 {
     $output = $this->render($error);
     $body = new Body(fopen('php://temp', 'r+'));
     $body->write($output);
     return $response->withStatus(500)->withHeader('Content-type', 'application/json')->withBody($body);
 }
 /**
  * @return string|null
  */
 public function getLastResponseStatus()
 {
     if (is_null($this->lastResponse)) {
         return null;
     }
     return $this->lastResponse->getStatusCode();
 }
Example #27
0
 public function __invoke(Request $request, Response $response, callable $next)
 {
     $xml = file_get_contents('php://input');
     $xml = preg_replace('/[\\n\\r]/', '', $xml);
     $xml = preg_replace('/>\\s+/', '>', $xml);
     $rootBodyClass = 'DTS\\eBaySDK\\Trading\\Types\\AbstractResponseType';
     $parserBody = new XmlParser($rootBodyClass);
     $body = mb_strstr($xml, "<soapenv:Body>", false);
     $body = trim($body, "<soapenv:Body>");
     $body = mb_strstr($body, "</soapenv:Body>", true);
     $body = '<' . $body;
     /** @var AbstractResponseType $notification */
     $notification = $parserBody->parse($body);
     $notification->NotificationSignature = mb_strstr($xml, '<ebl:NotificationSignature xmlns:ebl="urn:ebay:apis:eBLBaseComponents">', false);
     $notification->NotificationSignature = trim($notification->NotificationSignature, '<ebl:NotificationSignature xmlns:ebl="urn:ebay:apis:eBLBaseComponents">');
     $notification->NotificationSignature = mb_strstr($notification->NotificationSignature, "</ebl:NotificationSignature>", true);
     $timestamp = mb_strstr($body, "<Timestamp>", false);
     $timestamp = trim($timestamp, "<Timestamp>");
     $timestamp = mb_strstr($timestamp, "</Timestamp>", true);
     if ($this->calculationSignature($timestamp) !== $notification->NotificationSignature) {
         throw new \Exception("Not Equalse signature", 403);
     }
     $item = ['add_date' => $notification->Timestamp->format("Y-m-d h:i:s"), 'soapaction' => $notification->NotificationEventName, 'data' => $body];
     $this->store->create($item);
     return $response->withStatus(200);
 }
Example #28
0
 /**
  * @param ServerRequestInterface $request
  * @param ResponseInterface $response
  * @param callable $next
  * @return ResponseInterface
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     $key = $this->generateKey($request);
     $data = $this->cache->fetch($key);
     if (false !== $data) {
         list($body, $code, $headers) = unserialize($this->cache->fetch($key));
         $response->getBody()->write($body);
         $response = $response->withStatus($code);
         foreach (unserialize($headers) as $name => $value) {
             $response = $response->withHeader($name, $value);
         }
         return $response;
     }
     // prepare headers
     $ttl = $this->config['ttl'];
     $response = $next ? $next($request, $response) : $response;
     $response = $response->withHeader('Cache-Control', sprintf('public,max-age=%d,s-maxage=%d', $ttl, $ttl))->withHeader('ETag', $key);
     // save cache - status code, headers, body
     $body = $response->getBody()->__toString();
     $code = $response->getStatusCode();
     $headers = serialize($response->getHeaders());
     $data = serialize([$body, $code, $headers]);
     $this->cache->save($key, $data, $this->config['ttl']);
     return $response;
 }
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     if (false === strpos($response->getHeaderLine('Content-Type'), 'application/json')) {
         return $next($request, $response);
     }
     return $next($request, $response->withHeader('Content-Type', $this->contentType));
 }
 /**
  * Create a new instance of Mechanical Turk response
  *
  * @param ResponseInterface $response
  */
 public function __construct(ResponseInterface $response)
 {
     $this->status = $response->getStatusCode();
     $contents = new SimpleXmlElement($response->getBody()->getContents() ?: '<empty status="' . $this->status . '"></empty>');
     $this->isValid = count($contents->xpath('//Request[IsValid="True"]')) > 0;
     $this->content = json_decode(json_encode($contents));
 }