領収証発行サービス
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

131 line
2.8KB

  1. <?php
  2. namespace App\Files;
  3. use App\Jobs\File\DeleteFile;
  4. use App\Util\DateUtil;
  5. use Illuminate\Contracts\Filesystem\FileNotFoundException;
  6. use Illuminate\Support\Carbon;
  7. use Illuminate\Support\Facades\Storage;
  8. use Illuminate\Support\Str;
  9. class TmpFile
  10. {
  11. final protected const BASE_DIR = "/tmp";
  12. protected const DIR = [];
  13. /**
  14. * @param string $id
  15. * @return static
  16. * @throws FileNotFoundException
  17. */
  18. static public function loadFile(string $id, ...$other): static
  19. {
  20. $file = new static($id, $other);
  21. if (!$file->exists()) {
  22. throw new FileNotFoundException("ファイルが存在しません:" . $file->getFullPath());
  23. }
  24. return $file;
  25. }
  26. protected string $uuid;
  27. public function __construct(?string $id = null)
  28. {
  29. if ($id === null) {
  30. $this->uuid = Str::uuid();
  31. } else {
  32. $this->uuid = $id;
  33. }
  34. }
  35. public function __destruct()
  36. {
  37. // 消し忘れ防止のため、削除を予約しておく
  38. if ($this->exists()) {
  39. $lifeTimeMin = config("filesystems.tmpFile.lifetime", 60);
  40. $this->delete(DateUtil::now()->addMinutes($lifeTimeMin));
  41. }
  42. }
  43. protected function getFileTypeName()
  44. {
  45. return "tmp";
  46. }
  47. protected function getFileExtension(): string
  48. {
  49. return "tmp";
  50. }
  51. final protected function getFileName(): string
  52. {
  53. return sprintf("%s_%s.%s", $this->getFileTypeName(), $this->uuid, $this->getFileExtension());
  54. }
  55. public function getId(): string
  56. {
  57. return $this->uuid;
  58. }
  59. public function getPath()
  60. {
  61. return implode(
  62. "/",
  63. [
  64. self::BASE_DIR,
  65. ...static::DIR
  66. ]
  67. ) . "/" . $this->getFileName();
  68. }
  69. public function getFullPath()
  70. {
  71. return Storage::path($this->getPath());
  72. }
  73. public function put(string $content)
  74. {
  75. Storage::put($this->getPath(), $content);
  76. }
  77. public function get()
  78. {
  79. return Storage::get($this->getPath());
  80. }
  81. public function append(string $content)
  82. {
  83. Storage::append($this->getPath(), $content);
  84. }
  85. public function download(string $name = "download")
  86. {
  87. return response()->download($this->getFullPath(), $name)->deleteFileAfterSend();
  88. }
  89. public function exists()
  90. {
  91. return Storage::exists($this->getPath());
  92. }
  93. public function delete(?Carbon $delay = null): void
  94. {
  95. if ($delay === null) {
  96. $ret = Storage::delete($this->getPath());
  97. if ($ret) info(sprintf("ファイル削除:%s ", $this->getFullPath()));
  98. return;
  99. } else {
  100. DeleteFile::dispatch($this)
  101. ->delay($delay);
  102. return;
  103. }
  104. }
  105. }