/** * Action to handle a file upload * @param \ride\service\UploadService $uploadService * @return null */ public function uploadAction(UploadService $uploadService) { $api = new JsonApi(); $document = $api->createDocument(); $file = $this->request->getBodyParameter('file'); if (!is_array($file)) { $document->addError($api->createError(Response::STATUS_CODE_BAD_REQUEST, 'file.upload.none', 'No file uploaded')); } else { try { if (!isset($file['name']) || !isset($file['tmp_name']) || !array_key_exists('error', $file)) { throw new FileSystemException('Invalid file structure provided'); } $uploadedFile = $uploadService->handleFileUpload($file['name'], $file['tmp_name'], $file['error']); $resource = $api->createResource('uploads', $uploadedFile->getName()); $resource->setAttribute('name', $uploadedFile->getName()); $resource->setAttribute('mime', $file['type']); $resource->setAttribute('size', $file['size']); $document->setResourceData('uploads', $resource); } catch (FileSystemException $exception) { $document->addError($api->createError(Response::STATUS_CODE_BAD_REQUEST, 'file.upload.error', 'Error occured while processing the file upload', $exception->getMessage())); } } $this->setJsonView($document); $this->response->setStatusCode($document->getStatusCode()); $this->response->setHeader(Header::HEADER_CONTENT_TYPE, JsonApi::CONTENT_TYPE); }
/** * Adapts the data to a API resource * @param string $type Name of the resource type * @param mixed $data Data object to adapt * @return JsonApiResource */ protected function adaptResource($type, $data) { if ($data === null) { return null; } elseif (!$this->api) { throw new JsonApiException('Could not adapt resource: no API set to the document'); } $resourceAdapter = $this->api->getResourceAdapter($type); return $resourceAdapter->getResource($data, $this); }