GzipDownloader.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer\Downloader;
  12. use Composer\Config;
  13. use Composer\Cache;
  14. use Composer\EventDispatcher\EventDispatcher;
  15. use Composer\Package\PackageInterface;
  16. use Composer\Util\Platform;
  17. use Composer\Util\ProcessExecutor;
  18. use Composer\Util\HttpDownloader;
  19. use Composer\IO\IOInterface;
  20. /**
  21. * GZip archive downloader.
  22. *
  23. * @author Pavel Puchkin <i@neoascetic.me>
  24. */
  25. class GzipDownloader extends ArchiveDownloader
  26. {
  27. /** @var ProcessExecutor */
  28. protected $process;
  29. public function __construct(IOInterface $io, Config $config, HttpDownloader $downloader, EventDispatcher $eventDispatcher = null, Cache $cache = null, ProcessExecutor $process = null)
  30. {
  31. $this->process = $process ?: new ProcessExecutor($io);
  32. parent::__construct($io, $config, $downloader, $eventDispatcher, $cache);
  33. }
  34. protected function extract(PackageInterface $package, $file, $path)
  35. {
  36. $filename = pathinfo(parse_url($package->getDistUrl(), PHP_URL_PATH), PATHINFO_FILENAME);
  37. $targetFilepath = $path . DIRECTORY_SEPARATOR . $filename;
  38. // Try to use gunzip on *nix
  39. if (!Platform::isWindows()) {
  40. $command = 'gzip -cd ' . ProcessExecutor::escape($file) . ' > ' . ProcessExecutor::escape($targetFilepath);
  41. if (0 === $this->process->execute($command, $ignoredOutput)) {
  42. return;
  43. }
  44. if (extension_loaded('zlib')) {
  45. // Fallback to using the PHP extension.
  46. $this->extractUsingExt($file, $targetFilepath);
  47. return;
  48. }
  49. $processError = 'Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput();
  50. throw new \RuntimeException($processError);
  51. }
  52. // Windows version of PHP has built-in support of gzip functions
  53. $this->extractUsingExt($file, $targetFilepath);
  54. }
  55. private function extractUsingExt($file, $targetFilepath)
  56. {
  57. $archiveFile = gzopen($file, 'rb');
  58. $targetFile = fopen($targetFilepath, 'wb');
  59. while ($string = gzread($archiveFile, 4096)) {
  60. fwrite($targetFile, $string, Platform::strlen($string));
  61. }
  62. gzclose($archiveFile);
  63. fclose($targetFile);
  64. }
  65. }