public static function forUnexpectedContent(ResponseInterface $response, $expected)
 {
     $response->getBody()->rewind();
     $ex = new self(sprintf('Unexpected content in reponse. Expected a %s got %s', $expected, $response->getBody()->getContents()));
     $ex->responseObject = $response;
     return $ex;
 }
Exemple #2
0
 /**
  * @param ResponseInterface $response
  *
  * @return ApiResult
  */
 protected function _getResult($response)
 {
     if (!$response instanceof ResponseInterface) {
         throw new \InvalidArgumentException("{$response} should be an instance of ResponseInterface");
     }
     $result = new ApiResult();
     $result->setStatusCode($response->getStatusCode());
     $callId = $response->getHeader('X-Call-Id');
     if (!empty($callId)) {
         $result->setCallId($callId);
     }
     $decoded = json_decode((string) $response->getBody());
     if (isset($decoded->meta) && isset($decoded->data) && isset($decoded->meta->code) && $decoded->meta->code == $response->getStatusCode()) {
         $meta = $decoded->meta;
         $data = $decoded->data;
         if (isset($meta->message)) {
             $result->setStatusMessage($meta->message);
         }
         $result->setContent(json_encode($data));
     } else {
         $result->setContent((string) $response->getBody());
     }
     $result->setHeaders($response->getHeaders());
     return $result;
 }
 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();
 }
 /**
  * Turns an HTTP response object, with JSON in the body, into an array
  */
 public function convertIncomingResponseToArray(ResponseInterface $response) : array
 {
     $response->getBody()->rewind();
     $body = $response->getBody()->getContents();
     $bodyArray = json_decode($body, true);
     return $bodyArray ?: [];
 }
 /**
  * @return string|null
  */
 public function getLastResponseData()
 {
     if (is_null($this->lastResponse)) {
         return null;
     }
     return $this->lastResponse->getBody()->getContents();
 }
Exemple #6
0
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
 {
     $accessToken = Helper::getTokenFromReq($request);
     if ($accessToken == null) {
         $res['ret'] = 0;
         $res['msg'] = "token is null";
         $response->getBody()->write(json_encode($res));
         return $response;
     }
     $storage = Factory::createTokenStorage();
     $token = $storage->get($accessToken);
     if ($token == null) {
         $res['ret'] = 0;
         $res['msg'] = "token is null";
         $response->getBody()->write(json_encode($res));
         return $response;
     }
     if ($token->expireTime < time()) {
         $res['ret'] = 0;
         $res['msg'] = "token is expire";
         $response->getBody()->write(json_encode($res));
         return $response;
     }
     $response = $next($request, $response);
     return $response;
 }
 /**
  * Get content of response.
  *
  * @param bool $parseJsonToObject Parse JSON response to PHP object?
  *
  * @return string|object
  * @throws ComicApiException
  */
 public function getResponse($parseJsonToObject = false)
 {
     if ($this->response instanceof ResponseInterface) {
         return $this->response->getBody();
     }
     throw new ComicApiException("You can't get response without making request.");
 }
 /**
  * Outputs the error popup, or a plain message, depending on the response content type.
  *
  * @param \Exception|\Error      $exception Note: can't be type hinted, for PHP7 compat.
  * @param ResponseInterface|null $response  If null, it outputs directly to the client. Otherwise, it assumes the
  *                                          object is a new blank response.
  * @return ResponseInterface|null
  */
 static function display($exception, ResponseInterface $response = null)
 {
     // For HTML pages, output the error popup
     if (strpos(get($_SERVER, 'HTTP_ACCEPT'), 'text/html') !== false) {
         ob_start();
         ErrorConsoleRenderer::renderStyles();
         $stackTrace = self::getStackTrace($exception->getPrevious() ?: $exception);
         ErrorConsoleRenderer::renderPopup($exception, self::$appName, $stackTrace);
         $popup = ob_get_clean();
         // PSR-7 output
         if ($response) {
             $response->getBody()->write($popup);
             return $response->withStatus(500);
         }
         // Direct output
         echo $popup;
     } else {
         // PSR-7 output
         if ($response) {
             $response->getBody()->write($exception->getMessage());
             if (self::$devEnv) {
                 $response->getBody()->write("\n\nStack trace:\n" . $exception->getTraceAsString());
             }
             return $response->withoutHeader('Content-Type')->withHeader('Content-Type', 'text-plain')->withStatus(500);
         }
         // Direct output
         header("Content-Type: text/plain");
         http_response_code(500);
         echo $exception->getMessage();
         if (self::$devEnv) {
             echo "\n\nStack trace:\n" . $exception->getTraceAsString();
         }
     }
     return null;
 }
    public function dispatch(ServerRequestInterface $request, ResponseInterface $response) : ResponseInterface
    {
        $lang = LanguageNegotiator::getLanguage($request);
        $query = $this->db->prepare('SELECT n.id, n.title, n.parent_id from nodes n
INNER JOIN node_attributes na ON na.node_id = n.id
INNER JOIN attribute_values av on na.`attribute_value_id` = av.`id`
where av.`attribute_value` = :language;');
        $query->bindParam(':language', $lang);
        $query->execute();
        $data = $query->fetchAll(\PDO::FETCH_ASSOC);
        $neg = new FormatNegotiator();
        $contentType = $neg->getFormat($request);
        switch ($contentType) {
            case 'xml':
                $xml = new \SimpleXMLElement('<root/>');
                array_walk_recursive($this->treeBuilder->build($data), array($xml, 'addChild'));
                $response->getBody()->write($xml->asXML());
                break;
            default:
                $response->getBody()->write(json_encode($this->treeBuilder->build($data)));
                break;
        }
        return $response->withoutHeader('Content-Type');
        // Remove the Content-Type Header
    }
 /**
  * @param callable $fn
  */
 public function parseStream(callable $fn)
 {
     $body = $this->response->getBody();
     while (!$body->eof()) {
         $data = $this->parseEventData($body->read(1024));
         $fn($data);
     }
 }
Exemple #11
0
 public function getResponse()
 {
     if ($this->response && ($body = $this->response->getBody())) {
         // Rewind response body in case it has already been read
         $body->seek(0, SEEK_SET);
     }
     return $this->response;
 }
Exemple #12
0
 /**
  * Retrieve the json encoded response as a php associative array
  *
  * @return array
  */
 public function asArray()
 {
     $stream = $this->response->getBody();
     if ($stream->eof()) {
         $stream->rewind();
     }
     return json_decode($stream->getContents(), true);
 }
 /**
  * @return \WoohooLabs\Yin\JsonApi\Document\AbstractErrorDocument
  */
 protected function createErrorDocument()
 {
     $errorDocument = new ErrorDocument();
     if ($this->includeOriginalBody === true) {
         $errorDocument->setMeta(["original" => json_decode($this->response->getBody(), true)]);
     }
     return $errorDocument;
 }
Exemple #14
0
 /**
  * Return response with JSON header and status.
  *
  * @param \Psr\Http\Message\ResponseInterface $response
  * @param int $status
  * @return mixed
  */
 public function to(ResponseInterface $response, $status = 200)
 {
     if ($this->isRender) {
         $response->getBody()->write($this->jsonEncode($this->data, $this->encodingOptions));
     } else {
         $response->getBody()->write($this->data);
     }
     return $response->withStatus($status)->withHeader('Content-Type', 'application/json;charset=utf-8');
 }
 /**
  * @param ResponseInterface $response
  * @return array
  * @throws SurvosException
  */
 protected function parseResponse($response)
 {
     $content = $response->getBody()->getContents();
     $data = json_decode($content, true);
     if (!is_array($data)) {
         throw new SurvosException("Bad data in server response: " . substr($response->getBody(), 0, 200));
     }
     return $data;
 }
 private function getResponse(ResponseInterface $httpResponse)
 {
     $response = new Response($httpResponse);
     if ($httpResponse->getBody()) {
         $resp = (string) $httpResponse->getBody();
         $decoded = json_decode($resp, true);
         $response->setBody($decoded);
     }
     return $response;
 }
Exemple #17
0
 /**
  * Return response with JSON header and status.
  *
  * @param \Psr\Http\Message\ResponseInterface $response
  * @param int $status
  * @return mixed
  */
 public function to(ResponseInterface $response, $status = 200)
 {
     if ($this->view) {
         $response->getBody()->write($this->engine()->render($this->view, $this->params));
     } else {
         if ($this->data) {
             $response->getBody()->write($this->data);
         }
     }
     return $response->withStatus($status);
 }
 /**
  * edit Respond body.
  *
  * @param $callback
  *
  * @return $this
  */
 public function editBody($callback)
 {
     /** @var \Zend\Diactoros\Stream $bodyObject */
     $bodyObject = $this->response->getBody();
     $responseBody = json_decode((string) $bodyObject, true);
     $editedResponseBody = $callback($responseBody);
     $bodyObject->detach();
     $bodyObject->attach('php://temp', 'wb+');
     $bodyObject->write(json_encode($editedResponseBody));
     return $this;
 }
Exemple #19
0
 public function sendResponse(ResponseInterface $response)
 {
     $headers = [];
     foreach ($response->getHeaders() as $name => $values) {
         $headers[$name] = implode(', ', $values);
     }
     $response->getBody()->rewind();
     $size = $response->getBody()->getSize();
     $this->writeHead($size > 0, $response->getStatusCode(), $response->getReasonPhrase(), $headers);
     $this->end($response->getBody()->getContents());
 }
 /**
  * @inheritdoc
  * @throws \Exception
  */
 public function getBody()
 {
     if (!is_callable([$this->response, 'getBody']) || !is_callable([$this->response->getBody(), 'getContents'])) {
         throw new \Exception('Could not retrieve response body');
     }
     $body = json_decode($this->response->getBody()->getContents(), true);
     if (empty($body)) {
         throw new \Exception('Could not retrieve response body');
     }
     return $body;
 }
 /**
  * Maps a response body to an object.
  *
  * @param ResponseInterface $response
  * @param string            $class
  * @param string            $format
  *
  * @return object
  */
 public function map(ResponseInterface $response, $class, $format)
 {
     if ('json' === $format) {
         $hal = Hal::fromJson((string) $response->getBody(), 10);
     } elseif ('xml' === $format) {
         $hal = Hal::fromXml((string) $response->getBody(), 10);
     } else {
         throw new InvalidArgumentException(sprintf('Unsupported format "%s".', $format));
     }
     return $this->serializer->fromArray($this->getDataFromHal($hal, $class), $class);
 }
 /**
  * Inject the Content-Length header if is not already present.
  *
  * @param ResponseInterface $response
  * @return ResponseInterface
  */
 private function injectContentLength(ResponseInterface $response)
 {
     if (!$response->hasHeader('Content-Length')) {
         // PSR-7 indicates int OR null for the stream size; for null values,
         // we will not auto-inject the Content-Length.
         if (null !== $response->getBody()->getSize()) {
             return $response->withHeader('Content-Length', (string) $response->getBody()->getSize());
         }
     }
     return $response;
 }
 /**
  * Checks if a HTTP response is a valid API response
  * @param  PsrHttpMessageResponseInterface $response The response to check
  * @return PsrHttpMessageResponseInterface           The same response
  * @throws InvalidResponseException
  */
 public static function validateResponse(\Psr\Http\Message\ResponseInterface $response)
 {
     $data = json_decode($response->getBody());
     if ($response->getStatusCode() >= 400 && $response->getStatusCode() < 500) {
         if (false === $data || !is_object($data)) {
             throw new ClientException('Your request returned an error: ' . $response->getStatusCode() . ' ' . $response->getReasonPhrase(), $response->getStatusCode());
         }
     }
     if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 300 && $response->getStatusCode() < 400 || $response->getStatusCode() >= 500) {
         throw new APIException('Unsuccessful API call. Response status: ' . $response->getStatusCode() . ' ' . $response->getReasonPhrase(), $response->getStatusCode(), null, $response);
     }
     if (null === $data && $response->getStatusCode() != 204) {
         $body = $response->getBody();
         $summary = '';
         if ($body->isSeekable()) {
             $size = $body->getSize();
             $summary = $body->read(120);
             $body->rewind();
             if ($size > 120 && strlen($summary) > 120) {
                 $summary .= ' (truncated...)';
             }
             // Matches any printable character, including unicode characters:
             // letters, marks, numbers, punctuation, spacing, and separators.
             if (preg_match('/[^\\pL\\pM\\pN\\pP\\pS\\pZ\\n\\r\\t]/', $summary)) {
                 $summary = '';
             }
         }
         $summary = $summary ? ' Body: ' . $summary : '';
         throw new InvalidResponseException('Response body must be valid JSON.' . $summary, 0, null, $response->getBody());
     }
     if ($data && isset($data->errors) && (is_array($data->errors) || $data->errors instanceof Traversable)) {
         $message = [];
         foreach ($data->errors as $error) {
             $m = $error->title;
             if (isset($error->detail)) {
                 $m .= ' - ' . $error->detail;
             }
             if (isset($error->source) && $error->source instanceof Traversable) {
                 $source = [];
                 foreach ($error->source as $k => $v) {
                     $source[] = $k . ':' . $v;
                 }
                 if ($source) {
                     $m .= ' (' . implode(';', $source) . ')';
                 }
             }
             $message[] = $m;
         }
         $message = 'API responded with code ' . $response->getStatusCode() . ' and the following error(s): ' . implode(', ', $message);
         throw new APIException($message, $response->getStatusCode());
     }
     return $response;
 }
 /**
  * Process an incoming error, along with associated request and response.
  *
  * Accepts an error, a server-side request, and a response instance, and
  * does something with them; if further processing can be done, it can
  * delegate to `$out`.
  *
  * @see MiddlewareInterface
  * @param mixed $error
  * @param Request $request
  * @param Response $response
  * @param null|callable $out
  * @return null|Response
  */
 public function __invoke($error, Request $request, Response $response, callable $out = null)
 {
     //Show error in browser if display_errors is on in php.ini
     if ($this->displayErrors) {
         $body = $response->getBody();
         $body->write($error);
         return $response->withBody($body);
     }
     $body = $response->getBody();
     $body->write('500 Internal Server Error');
     return $response->withStatus(500)->withBody($body);
 }
 /**
  * {@inheritDoc}
  * @throws \InvalidArgumentException
  * @throws \RuntimeException
  */
 public function __invoke(Payload $payload, ResponseInterface $response) : ResponseInterface
 {
     $response->getBody()->rewind();
     $response->getBody()->write(json_encode($payload));
     $headers = array_merge($this->headers, ['Content-Type' => 'application/json']);
     foreach ($headers as $header => $value) {
         $response = $response->withHeader($header, $value);
     }
     /** @var \bitExpert\Adrenaline\Domain\DomainPayload $payload */
     $status = $payload->getStatus() ?: 200;
     return $response->withStatus($status);
 }
 /**
  * Returns the response body as DOMDocument instance.
  *
  * @return DOMDocument
  */
 public function getDOMDocument()
 {
     if ($this->domDocument instanceof DOMDocument === false) {
         $this->domDocument = new DOMDocument('1.0', 'UTF-8');
         libxml_clear_errors();
         $previousSetting = libxml_use_internal_errors(true);
         @$this->domDocument->loadXML($this->response->getBody());
         libxml_clear_errors();
         libxml_use_internal_errors($previousSetting);
     }
     return $this->domDocument;
 }
 /**
  * Inject some code just before any tag.
  *
  * @param ResponseInterface $response
  * @param string            $code
  * @param string            $tag
  *
  * @return ResponseInterface
  */
 private function inject(ResponseInterface $response, $code, $tag = 'body')
 {
     $html = (string) $response->getBody();
     $pos = strripos($html, "</{$tag}>");
     if ($pos === false) {
         $response->getBody()->write($code);
         return $response;
     }
     $body = self::createStream();
     $body->write(substr($html, 0, $pos) . $code . substr($html, $pos));
     return $response->withBody($body);
 }
Exemple #28
0
 private function middlewareResponseBody(Response $response)
 {
     if ($this->response['contentType'] == 'redirect') {
         return $response->withHeader("Location", $this->response['redirect']);
     }
     if ($this->response['contentType'] == 'json') {
         $response->getBody()->write(json_encode($this->response['data']));
         return $response;
     }
     $response->getBody()->write($this->response['body']);
     return $response;
 }
 /**
  * Example middleware invokable class
  *
  * @param  \Psr\Http\Message\ServerRequestInterface $request  PSR7 request
  * @param  \Psr\Http\Message\ResponseInterface      $response PSR7 response
  * @param  callable                                 $next     Next middleware
  *
  * @return \Psr\Http\Message\ResponseInterface
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     $response->getBody()->write($request->getUri()->getPath());
     $response->getBody()->write($this->serect);
     $authToken = $this->getToken($request->getHeader('Authorization'));
     if (!$authToken) {
         $response = $response->withStatus(401);
     } else {
         $response->getBody()->write($authToken);
     }
     $response = $next($request, $response);
     return $response;
 }
Exemple #30
0
 /**
  * {@inheritDoc}
  * @throws RuntimeException
  */
 public function buildResponse(DomainPayloadInterface $domainPayload, ResponseInterface $response)
 {
     try {
         $response->getBody()->rewind();
         $response->getBody()->write(json_encode($domainPayload->getValues()));
         $headers = array_merge($this->headers, ['Content-Type' => 'application/json']);
         foreach ($headers as $header => $value) {
             $response = $response->withHeader($header, $value);
         }
         return $response->withStatus(200);
     } catch (Exception $e) {
         throw new RuntimeException('Response object could not be instantiated! ' . $e->getMessage());
     }
 }