12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- <?php
- namespace App\Services\File\Upload;
- use Illuminate\Support\Facades\Auth;
- use Illuminate\Support\Facades\Cache;
- use JetBrains\PhpStorm\ArrayShape;
- class ProgressBar
- {
- const CACHE_PREFIX = 'upload:progress';
- protected int $uploadedSize = 0;
- public function __construct(
- protected string $requestId,
- protected int $totalSize,
- )
- {
- throw_validation_if(Cache::has($this->getCacheKey()), 'Request ID are not allowed to be duplicated');
- $this->start();
- }
- public function increment(int $size): void
- {
- $this->uploadedSize += $size;
- Cache::put($this->getCacheKey(), $this->query(), now()->addHours(6));
- }
- public function start()
- {
- Cache::put($this->getCacheKey(), 0, now()->addMinutes(30));
- }
- public function completed()
- {
- Cache::put($this->getCacheKey(), 100.00, now()->addMinutes(30));
- }
- public function query(): float
- {
- return intval(($this->uploadedSize / $this->totalSize) * 100);
- }
- protected function getCacheKey()
- {
- return sprintf("%s:%s:%s", self::CACHE_PREFIX, Auth::id(), $this->requestId);
- }
- /**
- * @param string $uuid
- * @return array
- */
- #[ArrayShape(['status' => "string", 'progress' => "mixed"])]
- public static function queryByRequestId(string $uuid): array
- {
- $progress = Cache::get(sprintf("%s:%s:%s", self::CACHE_PREFIX, Auth::id(), $uuid));
- $status = "none";
- if (is_numeric($progress)) {
- if ($progress == 100) {
- $status = "completed";
- } else {
- $status = "uploading";
- }
- }
- return [
- 'status' => $status,
- 'progress' => $progress ?: 0
- ];
- }
- }
|