Created
August 3, 2017 07:39
-
-
Save beyerz/703d7a0993b8192cae4364873232417b to your computer and use it in GitHub Desktop.
Symfony console, download remote file with progress bar using guzzle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param SymfonyStyle $io | |
* @param $remotePath | |
* | |
* @return string | |
*/ | |
public function download(SymfonyStyle $io, $remotePath) | |
{ | |
$io->section("Download " . $remotePath); | |
$parts = parse_url($remotePath); | |
$filename = basename($parts['path']); | |
$progress = null; | |
$tmp = sys_get_temp_dir(); | |
$fileLocation = $tmp . DIRECTORY_SEPARATOR . $filename; | |
$handle = fopen($fileLocation, "w+"); | |
$guzzle = new Client(array( | |
'progress' => function ($total, $downloaded) use ($io, &$progress) { | |
if ($total > 0 && is_null($progress)) { | |
$progress = $io->createProgressBar($total); | |
$progress->start(); | |
} | |
if (!is_null($progress)) { | |
if ($total === $downloaded) { | |
$progress->finish(); | |
return; | |
} | |
$progress->setProgress($downloaded); | |
} | |
}, | |
'sink' => $handle, | |
)); | |
$guzzle->get($remotePath); | |
return $fileLocation; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment