GzipDownloader.php 2.5 KB

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