Exemplo n.º 1
0
 /**
  * @param \DreamFactory\Core\Contracts\ServiceResponseInterface $response
  * @param null                                                  $accepts
  * @param null                                                  $asFile
  * @param string                                                $resource
  *
  * @return \Symfony\Component\HttpFoundation\Response
  * @throws \DreamFactory\Core\Exceptions\BadRequestException
  * @throws \DreamFactory\Core\Exceptions\NotImplementedException
  */
 public static function sendResponse(ServiceResponseInterface $response, $accepts = null, $asFile = null, $resource = 'resource')
 {
     if (empty($accepts)) {
         $accepts = static::getAcceptedTypes();
     }
     if (empty($asFile)) {
         $asFile = \Request::input('file');
         if (true === filter_var($asFile, FILTER_VALIDATE_BOOLEAN)) {
             $asFile = $resource . '.json';
         }
         if (is_string($asFile) && strpos($asFile, '.') !== false) {
             $format = strtolower(pathinfo($asFile, PATHINFO_EXTENSION));
             if (!empty($format)) {
                 if ($format === 'csv') {
                     $accepts = ['text/csv'];
                 } else {
                     if ($format === 'xml') {
                         $accepts = ['application/xml'];
                     } else {
                         if ($format === 'json') {
                             $accepts = ['application/json'];
                         }
                     }
                 }
             }
         } else {
             $asFile = null;
         }
     }
     // If no accepts header supplied or a blank is supplied for
     // accept header (clients like bench-rest) then use default response type from config.
     if (empty($accepts) || isset($accepts[0]) && empty($accepts[0])) {
         $accepts[] = config('df.default_response_type');
     }
     $content = $response->getContent();
     $format = $response->getContentFormat();
     if (empty($content) && is_null($format)) {
         // No content and type specified. (File stream already handled by service)
         return null;
     }
     $status = $response->getStatusCode();
     //  In case the status code is not a valid HTTP Status code
     if (!in_array($status, HttpStatusCodes::getDefinedConstants())) {
         //  Do necessary translation here. Default is Internal server error.
         $status = HttpStatusCodeInterface::HTTP_INTERNAL_SERVER_ERROR;
     }
     if ($content instanceof \Exception) {
         $status = $content instanceof RestException ? $content->getStatusCode() : ServiceResponseInterface::HTTP_INTERNAL_SERVER_ERROR;
         $content = self::makeExceptionContent($content);
         $format = DataFormats::PHP_ARRAY;
     }
     // check if the current content type is acceptable for return
     $contentType = $response->getContentType();
     if (empty($contentType)) {
         $contentType = DataFormats::toMimeType($format, null);
     }
     // see if we match an accepts type, if so, go with it.
     $accepts = ArrayUtils::clean($accepts);
     if (!empty($contentType) && static::acceptedContentType($accepts, $contentType)) {
         return DfResponse::create($content, $status, ["Content-Type" => $contentType]);
     }
     // we don't have an acceptable content type, see if we can convert the content.
     $acceptsAny = false;
     $reformatted = false;
     foreach ($accepts as $acceptType) {
         $acceptFormat = DataFormats::fromMimeType($acceptType, null);
         $mimeType = false !== strpos($acceptType, ';') ? trim(strstr($acceptType, ';', true)) : $acceptType;
         if (is_null($acceptFormat)) {
             if ('*/*' === $mimeType) {
                 $acceptsAny = true;
             }
             continue;
         } else {
             $contentType = $mimeType;
         }
         $reformatted = DataFormatter::reformatData($content, $format, $acceptFormat);
     }
     $responseHeaders = ["Content-Type" => $contentType];
     if (!empty($asFile)) {
         $responseHeaders['Content-Disposition'] = 'attachment; filename="' . $asFile . '";';
     }
     if ($acceptsAny) {
         $contentType = empty($contentType) ? DataFormats::toMimeType($format, config('df.default_response_type')) : $contentType;
         $responseHeaders['Content-Type'] = $contentType;
         return DfResponse::create($content, $status, $responseHeaders);
     } else {
         if (false !== $reformatted) {
             return DfResponse::create($reformatted, $status, $responseHeaders);
         }
     }
     throw new BadRequestException('Content in response can not be resolved to acceptable content type.');
 }
Exemplo n.º 2
0
 /**
  * @param string $method
  * @param string $url
  * @param mixed  $payload
  * @param array  $curlOptions
  *
  * @return \DreamFactory\Core\Utility\ServiceResponse
  * @throws \DreamFactory\Core\Exceptions\NotImplementedException
  * @throws \DreamFactory\Core\Exceptions\RestException
  */
 protected static function externalRequest($method, $url, $payload = [], $curlOptions = [])
 {
     $result = Curl::request($method, $url, $payload, $curlOptions);
     $contentType = Curl::getInfo('content_type');
     $format = DataFormats::fromMimeType($contentType);
     $status = Curl::getLastHttpCode();
     if ($status >= 300) {
         if (!is_string($result)) {
             $result = json_encode($result);
         }
         throw new RestException($status, $result, $status);
     }
     return ResponseFactory::create($result, $format, $status, $contentType);
 }
Exemplo n.º 3
0
 /**
  * @throws \DreamFactory\Core\Exceptions\RestException
  * @return bool
  */
 protected function processRequest()
 {
     $data = $this->request->getContent();
     $resource = !empty($this->resourcePath) ? ltrim($this->resourcePath, '/') : null;
     if ($resource) {
         $this->url = rtrim($this->baseUrl, '/') . '/' . $resource;
     } else {
         $this->url = $this->baseUrl;
     }
     if (!empty($this->query)) {
         $splicer = false === strpos($this->baseUrl, '?') ? '?' : '&';
         $this->url .= $splicer . $this->query;
     }
     $cacheKey = '';
     if ($this->cacheEnabled) {
         switch ($this->action) {
             case Verbs::GET:
                 // build cache_key
                 $cacheKey = $this->action . ':' . $this->name;
                 if ($resource) {
                     $cacheKey .= ':' . $resource;
                 }
                 if (!empty($this->cacheQuery)) {
                     $cacheKey .= ':' . $this->cacheQuery;
                 }
                 $cacheKey = hash('sha256', $cacheKey);
                 if (null !== ($result = $this->getFromCache($cacheKey))) {
                     return $result;
                 }
                 break;
         }
     }
     Log::debug('Outbound HTTP request: ' . $this->action . ': ' . $this->url);
     Curl::setDecodeToArray(true);
     $result = Curl::request($this->action, $this->url, $data, $this->curlOptions);
     if (false === $result) {
         $error = Curl::getError();
         throw new RestException(ArrayUtils::get($error, 'code', 500), ArrayUtils::get($error, 'message'));
     }
     $status = Curl::getLastHttpCode();
     if ($status >= 300) {
         if (!is_string($result)) {
             $result = json_encode($result);
         }
         throw new RestException($status, $result, $status);
     }
     $contentType = Curl::getInfo('content_type');
     $format = DataFormats::fromMimeType($contentType);
     $response = ResponseFactory::create($result, $format, $status, $contentType);
     if ($this->cacheEnabled) {
         switch ($this->action) {
             case Verbs::GET:
                 $this->addToCache($cacheKey, $result);
                 break;
         }
     }
     return $response;
 }