Allows creating a response by passing data to the constructor; by default, serializes the data to JSON, sets a status code of 200 and sets the Content-Type header to application/json.
Inheritance: extends Zend\Diactoros\Response, use trait InjectContentTypeTrait
Example #1
0
 /**
  *
  * @todo Chenge format of JSON response from [{}] to {} for one row response?
  * @todo Add develope mode for debug with HTML POST and GET
  * @param ServerRequestInterface $request
  * @param ResponseInterface $response
  * @param callable|null $next
  * @return ResponseInterface
  * @throws \zaboy\rest\RestException
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
 {
     $responseBody = $request->getAttribute('Response-Body');
     $accept = $request->getHeaderLine('Accept');
     if (isset($accept) && preg_match('#^application/([^+\\s]+\\+)?json#', $accept)) {
         $status = $response->getStatusCode();
         $headers = $response->getHeaders();
         $response = new JsonResponse($responseBody, $status, $headers);
     } else {
         $escaper = new Escaper();
         $result = '';
         switch (true) {
             case gettype($responseBody) == 'array':
                 //                    foreach ($responseBody as $valueArray) {
                 //                        $result = $result . ' - ';
                 //                        if (is_array($valueArray)) {
                 //                            foreach ($valueArray as $key => $value) {
                 //                                $result = $result
                 //                                        . $escaper->escapeHtml($key)
                 //                                        . ' - '
                 //                                        . $escaper->escapeHtml(is_array($value) ? print_r($value, true) : $value)
                 //                                        . '; _   _  ';
                 //                            }
                 //                            $result = $result . '<br>' . PHP_EOL;
                 //                        } else {
                 //                            $result = $result . $escaper->escapeHtml($valueArray) . '<br>' . PHP_EOL;
                 //                        }
                 //                    }
                 $result = '<pre>' . $escaper->escapeHtml(print_r($responseBody, true)) . '</pre>';
                 break;
             case is_numeric($responseBody) or is_string($responseBody):
                 $result = $responseBody . '<br>' . PHP_EOL;
                 break;
             case is_bool($responseBody):
                 $result = $responseBody ? 'TRUE' : 'FALSE';
                 $result = $result . '<br>' . PHP_EOL;
                 break;
             default:
                 throw new \zaboy\rest\RestException('$responseBody must be array, numeric or bool. But ' . gettype($responseBody) . ' given.');
         }
         $response->getBody()->write($result);
     }
     if ($next) {
         return $next($request, $response);
     }
     return $response;
 }
Example #2
0
 /**
  * {@inheritdoc}
  */
 public function __construct(Document $document, $status = 200, array $headers = [], $encodingOptions = 15)
 {
     $headers['content-type'] = 'application/vnd.api+json';
     // The call to jsonSerialize prevents rare issues with json_encode() failing with a
     // syntax error even though Document implements the JsonSerializable interface.
     // See https://github.com/flarum/core/issues/685
     parent::__construct($document->jsonSerialize(), $status, $headers, $encodingOptions);
 }
 public function prepareResponse($result)
 {
     if ($result instanceof ApiProblem) {
         $response = new JsonResponse($result->toArray());
         return $response->withStatus($result->status);
     } elseif ($result instanceof JsonResponse) {
         return $result;
     } elseif ($result instanceof \Zend\Paginator\Paginator) {
         return new JsonResponse((array) $result->getCurrentItems());
     } elseif (is_object($result) && method_exists($result, 'toArray')) {
         return new JsonResponse($result->toArray());
     } elseif ($result instanceof \Traversable) {
         return new JsonResponse((array) $result);
     } elseif (is_array($result)) {
         return new JsonResponse($result);
     }
     return $this->prepareResponse(new ApiProblem(502));
 }
 /**
  * Constructor
  *
  * @todo Customize according to project
  * @param array $errors Errors
  */
 public function __construct(array $errors)
 {
     parent::__construct(['status' => 'error', 'errors' => $errors], 422);
 }
 /**
  * @param mixed $code
  * @param int $message
  */
 public function __construct($code, $message)
 {
     $responseData = ['code' => $code, 'message' => $message, 'reference' => ''];
     parent::__construct($responseData, $code);
 }
 /**
  * Create an empty response with the 404 status code
  *
  * @param mixed $data Explanation
  * @param array $headers Headers for the response, if any.
  */
 public function __construct($data, array $headers = [])
 {
     parent::__construct($data, 404, $headers);
 }
Example #7
0
 /**
  * {@inheritdoc}
  */
 public function __construct(Document $document, $status = 200, array $headers = [], $encodingOptions = 15)
 {
     $headers['content-type'] = 'application/vnd.api+json';
     parent::__construct($document, $status, $headers, $encodingOptions);
 }
 private function throwJsonException($message, $status)
 {
     // Ensure a valid HTTP status
     if (!is_numeric($status) || $status < 400 || $status > 599) {
         $status = 500;
     }
     $response = new JsonResponse([], $status);
     $errors = ['errors' => ['status' => $response->getReasonPhrase() ? $status : 400, 'title' => $response->getReasonPhrase() ?: 'Bad Request', 'detail' => $message, 'links' => ['related' => 'http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html']]];
     return new JsonResponse($errors, $response->getStatusCode());
 }
Example #9
0
 /**
  * JsonResponse overloaded Constructor to assign JSON-API Content-Type
  * and require JsonApi\Document instance as body
  */
 public function __construct(Document $document, $status = 200, array $headers = [], $encodingOptions = self::DEFAULT_JSON_FLAGS)
 {
     $headers['Content-Type'] = 'application/vnd.api+json';
     parent::__construct($document->toArray(), $status, $headers, $encodingOptions);
 }