ZipDownloader.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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\Package\PackageInterface;
  13. /**
  14. * @author Jordi Boggiano <j.boggiano@seld.be>
  15. */
  16. class ZipDownloader
  17. {
  18. public function download(PackageInterface $package, $path)
  19. {
  20. if (!class_exists('ZipArchive')) {
  21. throw new \UnexpectedValueException('You need the zip extension enabled to use the ZipDownloader');
  22. }
  23. $tmpName = tempnam(sys_get_temp_dir(), '');
  24. $this->downloadFile($package->getSourceUrl(), $tmpName);
  25. if (!file_exists($tmpName)) {
  26. throw new \UnexpectedValueException($path.' could not be saved into '.$tmpName.', make sure the'
  27. .' directory is writable and you have internet connectivity.');
  28. }
  29. $zipArchive = new ZipArchive();
  30. if (true === ($retval = $zipArchive->open($tmpName))) {
  31. $zipArchive->extractTo($path.'/'.$package->getName());
  32. $zipArchive->close();
  33. } else {
  34. throw new \UnexpectedValueException($tmpName.' is not a valid zip archive, got error code '.$retval);
  35. }
  36. }
  37. protected function downloadFile ($url, $path)
  38. {
  39. $file = fopen($url, "rb");
  40. if ($file) {
  41. $newf = fopen($path, "wb");
  42. if ($newf) {
  43. while (!feof($file)) {
  44. fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
  45. }
  46. }
  47. }
  48. if ($file) {
  49. fclose($file);
  50. }
  51. if ($newf) {
  52. fclose($newf);
  53. }
  54. }
  55. }