factory = $factory ?? fn (string $url, string $target): FileDownload => new FileDownload($url, $target); @mkdir(dirname($target), 0777, true); @unlink($target); if (@file_put_contents($target . '.part', '') === false) { $this->fail('impossible d\'écrire ' . $target); return; } $this->next(); } private function next(): void { if ($this->size <= 0) { $this->part = ($this->factory)($this->url, $this->target . '.range'); return; } $to = min($this->from + $this->chunk, $this->size) - 1; $this->part = ($this->factory)($this->url . (str_contains($this->url, '?') ? '&' : '?') . 'range=' . $this->from . '-' . $to, $this->target . '.range'); } /** Each frame. @return bool true once it ended (ok() or error) */ public function poll(): bool { if ($this->done || $this->part === null) { return $this->done; } $part = $this->part; $ended = $part->poll(); $this->progress = $this->size > 0 ? min(0.999, ($this->from + $part->received) / $this->size) : $part->progress; $this->received = $this->from + $part->received; if (!$ended) { return false; } $this->part = null; if (!$part->ok()) { if (++$this->tries < self::TRIES) { $this->next(); // the same range again return false; } $this->fail($part->error); return true; } $this->tries = 0; $got = (int)@filesize($this->target . '.range'); if (!$this->append($this->target . '.range')) { return true; } $this->from += $got; if ($this->size > 0 && $this->from < $this->size && $got > 0) { $this->next(); return false; } if ($this->size > 0 && $this->from < $this->size) { $this->fail(sprintf('téléchargement coupé (%d / %d octets)', $this->from, $this->size)); return true; } @unlink($this->target); if (!@rename($this->target . '.part', $this->target)) { $this->fail('impossible d\'écrire ' . $this->target); return true; } $this->progress = 1.0; $this->done = true; return true; } private function append(string $file): bool { $in = @fopen($file, 'rb'); $out = @fopen($this->target . '.part', 'ab'); $ok = $in !== false && $out !== false && stream_copy_to_stream($in, $out) !== false; $in !== false && fclose($in); $out !== false && fclose($out); @unlink($file); if (!$ok) { $this->fail('impossible d\'écrire ' . $this->target); } return $ok; } public function ok(): bool { return $this->done && $this->error === ''; } /** Stopped for good: its files removed. */ public function cancel(): void { $this->part?->cancel(); $this->part = null; if (!$this->done) { $this->fail('arrêté'); } } private function fail(string $message): void { $this->error = $message; $this->done = true; @unlink($this->target . '.part'); @unlink($this->target . '.range'); } }