You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.1 KiB

  1. <?php
  2. namespace App\Service;
  3. use App\Constants\ErrorCode;
  4. use League\Flysystem\FilesystemNotFoundException;
  5. class AttachmentService implements AttachmentServiceInterface
  6. {
  7. /**
  8. * @inheritDoc
  9. */
  10. public function formUpload($file, $path, $filesystem, $attachmenttype = 'image')
  11. {
  12. $fileRealPath = $file->getRealPath();
  13. $fileHash = md5_file($fileRealPath);
  14. $path = $this->getBasePath($path, $attachmenttype);
  15. $fileName = $path . '/' . $fileHash . '.' . $file->getExtension();
  16. if ($filesystem->has($fileName)) {
  17. return $fileName;
  18. }
  19. $stream = fopen($fileRealPath, 'r+');
  20. $filesystem->writeStream($fileName, $stream);
  21. fclose($stream);
  22. return $fileName;
  23. }
  24. /**
  25. * @inheritDoc
  26. */
  27. public function base64Upload($contents, $path, $filesystem)
  28. {
  29. preg_match('/^(data:\s*image\/(\w+);base64,)/', $contents, $result);
  30. if (empty($result)) {
  31. throw new FilesystemNotFoundException(ErrorCode::getMessage(ErrorCode::UPLOAD_INVALID),ErrorCode::UPLOAD_INVALID);
  32. }
  33. $contents = base64_decode(str_replace($result[1], '', $contents));
  34. $fileHash = md5($contents);
  35. $path = $this->getBasePath($path);
  36. $fileName = $path . '/' . $fileHash . '.' . $result[2];
  37. if ($filesystem->has($fileName)) {
  38. return $fileName;
  39. }
  40. $filesystem->write($fileName, $contents);
  41. return $fileName;
  42. }
  43. protected function getBasePath($path, $attachmenttype = 'image')
  44. {
  45. switch ($attachmenttype) {
  46. case 'image':
  47. $baseDir = env('IMAGE_BASE', '/attachment/images');
  48. break;
  49. case 'file':
  50. $baseDir = env('FILES_BASE', '/attachment/files');
  51. break;
  52. default:
  53. $baseDir = env('FILES_BASE', '/attachment');
  54. break;
  55. }
  56. $path = $path ? '/'.$path : '';
  57. $path .= '/'.date('Y').'/'.date('m').'/'.date('d');
  58. return $baseDir.$path;
  59. }
  60. }