ProgressBar.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace App\Services\File\Upload;
  3. use Illuminate\Support\Facades\Auth;
  4. use Illuminate\Support\Facades\Cache;
  5. use JetBrains\PhpStorm\ArrayShape;
  6. class ProgressBar
  7. {
  8. const CACHE_PREFIX = 'upload:progress';
  9. protected int $uploadedSize = 0;
  10. public function __construct(
  11. protected string $requestId,
  12. protected int $totalSize,
  13. )
  14. {
  15. throw_validation_if(Cache::has($this->getCacheKey()), 'Request ID are not allowed to be duplicated');
  16. $this->start();
  17. }
  18. public function increment(int $size): void
  19. {
  20. $this->uploadedSize += $size;
  21. Cache::put($this->getCacheKey(), $this->query(), now()->addHours(6));
  22. }
  23. public function start()
  24. {
  25. Cache::put($this->getCacheKey(), 0, now()->addMinutes(30));
  26. }
  27. public function completed()
  28. {
  29. Cache::put($this->getCacheKey(), 100.00, now()->addMinutes(30));
  30. }
  31. public function query(): float
  32. {
  33. return intval(($this->uploadedSize / $this->totalSize) * 100);
  34. }
  35. protected function getCacheKey()
  36. {
  37. return sprintf("%s:%s:%s", self::CACHE_PREFIX, Auth::id(), $this->requestId);
  38. }
  39. /**
  40. * @param string $uuid
  41. * @return array
  42. */
  43. #[ArrayShape(['status' => "string", 'progress' => "mixed"])]
  44. public static function queryByRequestId(string $uuid): array
  45. {
  46. $progress = Cache::get(sprintf("%s:%s:%s", self::CACHE_PREFIX, Auth::id(), $uuid));
  47. $status = "none";
  48. if (is_numeric($progress)) {
  49. if ($progress == 100) {
  50. $status = "completed";
  51. } else {
  52. $status = "uploading";
  53. }
  54. }
  55. return [
  56. 'status' => $status,
  57. 'progress' => $progress ?: 0
  58. ];
  59. }
  60. }