/** * @param int $from The format of the information * @param int $to The format to translate to * @param mixed $subject THe information to translate * @param mixed $translated Holds the translated subject value * * @return bool * @throws BadRequestException */ public static function translate($from, $to, $subject, &$translated) { $result = true; $translated = $subject; if (!DataFormats::contains($from) || !DataFormats::contains($to)) { throw new BadRequestException('Invalid data format specified'); } // Translate! switch ($from) { // PHP array & object case DataFormats::PHP_ARRAY: case DataFormats::PHP_OBJECT: switch ($to) { // JSON string case DataFormats::JSON: if (false === ($translated = json_encode($subject, JSON_UNESCAPED_SLASHES))) { if (JSON_ERROR_NONE !== json_last_error()) { $result = false; $translated = $subject; } } break; default: $result = false; break; } break; // JSON string // JSON string case DataFormats::JSON: switch ($to) { // PHP array & object case DataFormats::PHP_ARRAY: case DataFormats::PHP_OBJECT: if (false === ($translated = json_decode($subject, DataFormats::PHP_ARRAY == $from))) { if (JSON_ERROR_NONE !== json_last_error()) { $translated = $subject; $result = false; } } break; default: $result = false; break; } break; default: $result = false; break; } return $result; }
/** * Execute the console command. * * @return mixed */ public function handle() { try { $data = $this->argument('data'); if (filter_var($data, FILTER_VALIDATE_URL)) { // need to download file $data = FileUtilities::importUrlFileToTemp($data); } if (is_file($data)) { $data = file_get_contents($data); } $format = $this->option('format'); $format = DataFormats::toNumeric($format); $this->comment($format); $service = $this->option('service'); $resource = $this->option('resource'); $result = ServiceHandler::handleRequest(Verbs::POST, $service, $resource, [], $data, $format); $this->info('Import complete!'); } catch (\Exception $e) { $this->error($e->getMessage()); } }
/** * @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); }
/** * @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.'); }
/** * @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; }
/** * @param null $key * @param null $default * * @return array * @throws BadRequestException */ public function getPayloadData($key = null, $default = null) { if (!empty($this->contentAsArray)) { if (null === $key) { return $this->contentAsArray; } else { return ArrayUtils::get($this->contentAsArray, $key, $default); } } //This just checks the Request Header Content-Type. if (Request::isJson()) { // Decoded json data is cached internally using parameterBag. return $this->json($key, $default); } if (Str::contains(Request::header('CONTENT_TYPE'), 'xml')) { // Formatted xml data is stored in $this->contentAsArray return $this->xml($key, $default); } if (Str::contains(Request::header('CONTENT_TYPE'), 'csv')) { // Formatted csv data is stored in $this->contentAsArray return $this->csv($key, $default); } //Check the actual content. If it is blank return blank array. $content = $this->getContent(); if (empty($content)) { if (null === $key) { return []; } else { return $default; } } //Checking this last to be more efficient. if (json_decode($content) !== null) { $this->contentType = DataFormats::toMimeType(DataFormats::JSON); //Decoded json data is cached internally using parameterBag. return $this->json($key, $default); } else { if (DataFormatter::xmlToArray($content) !== null) { $this->contentType = DataFormats::toMimeType(DataFormats::XML); return $this->xml($key, $default); } else { if (!empty(DataFormatter::csvToArray($content))) { $this->contentType = DataFormats::toMimeType(DataFormats::CSV); return $this->csv($key, $default); } } } throw new BadRequestException('Unrecognized payload type'); }