GzipDownloader.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. protected $process;
  28. public function __construct(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null, Cache $cache = null, ProcessExecutor $process = null, HttpDownloader $downloader = null)
  29. {
  30. $this->process = $process ?: new ProcessExecutor($io);
  31. parent::__construct($io, $config, $eventDispatcher, $cache, $downloader);
  32. }
  33. protected function extract($file, $path)
  34. {
  35. $targetFilepath = $path . DIRECTORY_SEPARATOR . basename(substr($file, 0, -3));
  36. // Try to use gunzip on *nix
  37. if (!Platform::isWindows()) {
  38. $command = 'gzip -cd ' . ProcessExecutor::escape($file) . ' > ' . ProcessExecutor::escape($targetFilepath);
  39. if (0 === $this->process->execute($command, $ignoredOutput)) {
  40. return;
  41. }
  42. if (extension_loaded('zlib')) {
  43. // Fallback to using the PHP extension.
  44. $this->extractUsingExt($file, $targetFilepath);
  45. return;
  46. }
  47. $processError = 'Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput();
  48. throw new \RuntimeException($processError);
  49. }
  50. // Windows version of PHP has built-in support of gzip functions
  51. $this->extractUsingExt($file, $targetFilepath);
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. protected function getFileName(PackageInterface $package, $path)
  57. {
  58. return $path.'/'.pathinfo(parse_url($package->getDistUrl(), PHP_URL_PATH), PATHINFO_BASENAME);
  59. }
  60. private function extractUsingExt($file, $targetFilepath)
  61. {
  62. $archiveFile = gzopen($file, 'rb');
  63. $targetFile = fopen($targetFilepath, 'wb');
  64. while ($string = gzread($archiveFile, 4096)) {
  65. fwrite($targetFile, $string, Platform::strlen($string));
  66. }
  67. gzclose($archiveFile);
  68. fclose($targetFile);
  69. }
  70. }