DocumentUploadController.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace Controllers;
  3. use Libs\MultipartFormDataParser;
  4. use Libs\ResponseLib;
  5. use Models\DocumentModel;
  6. use Psr\Http\Message\ServerRequestInterface;
  7. use Services\DocumentStorageService;
  8. class DocumentUploadController
  9. {
  10. private DocumentModel $documentModel;
  11. private DocumentStorageService $storage;
  12. public function __construct()
  13. {
  14. $this->documentModel = new DocumentModel();
  15. $this->storage = new DocumentStorageService();
  16. }
  17. public function __invoke(ServerRequestInterface $request)
  18. {
  19. $userId = (int)($request->getAttribute('api_user_id') ?? 0);
  20. $companyId = (int)($request->getAttribute('api_company_id') ?? 0);
  21. if ($userId <= 0 || $companyId <= 0) {
  22. return ResponseLib::sendFail('Unauthorized', [], 'E_VALIDATE')->withStatus(401);
  23. }
  24. try {
  25. $parsed = MultipartFormDataParser::parse($request);
  26. } catch (\Throwable $e) {
  27. return ResponseLib::sendFail('Invalid multipart form-data: ' . $e->getMessage(), [], 'E_VALIDATE')->withStatus(400);
  28. }
  29. $fields = $parsed['fields'] ?? [];
  30. $files = $parsed['files'] ?? [];
  31. $documentType = isset($fields['document_type']) ? (string)$fields['document_type'] : '';
  32. if ($documentType === '') {
  33. return ResponseLib::sendFail('Missing field: document_type', [], 'E_VALIDATE')->withStatus(400);
  34. }
  35. $file = $files['file'] ?? null;
  36. if (!is_array($file) || !isset($file['content'])) {
  37. return ResponseLib::sendFail('Missing file field: file', [], 'E_VALIDATE')->withStatus(400);
  38. }
  39. $originalFilename = (string)($file['filename'] ?? 'upload.bin');
  40. $contentType = (string)($file['content_type'] ?? 'application/octet-stream');
  41. $content = (string)$file['content'];
  42. try {
  43. $documentType = $this->storage->sanitizeDocumentType($documentType);
  44. $dir = $this->storage->ensureDirectory($companyId, $userId, $documentType);
  45. $storedFilename = $this->storage->buildStoredFilename($originalFilename, $contentType);
  46. $storedPath = $this->storage->writeFile($dir, $storedFilename, $content);
  47. $created = $this->documentModel->create($userId, $documentType, $storedPath);
  48. return ResponseLib::sendOk($created, 'S_CREATED');
  49. } catch (\Throwable $e) {
  50. return ResponseLib::sendFail('Upload failed: ' . $e->getMessage(), [], 'E_INTERNAL')->withStatus(500);
  51. }
  52. }
  53. }