ZipDownloader.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 implements DownloaderInterface
  17. {
  18. public function download(PackageInterface $package, $path, $url, $checksum = null)
  19. {
  20. if (!class_exists('ZipArchive')) {
  21. throw new \UnexpectedValueException('You need the zip extension enabled to use the ZipDownloader');
  22. }
  23. $targetPath = $path . "/" . $package->getName();
  24. if (!is_dir($targetPath)) {
  25. if (file_exists($targetPath)) {
  26. throw new \UnexpectedValueException($targetPath.' exists and is not a directory.');
  27. }
  28. if (!mkdir($targetPath, 0777, true)) {
  29. throw new \UnexpectedValueException($targetPath.' does not exist and could not be created.');
  30. }
  31. }
  32. $zipName = $targetPath.'/'.basename($url, '.zip').'.zip';
  33. echo 'Downloading '.$url.' to '.$zipName.PHP_EOL;
  34. copy($url, $zipName);
  35. if (!file_exists($zipName)) {
  36. throw new \UnexpectedValueException($path.' could not be saved into '.$zipName.', make sure the'
  37. .' directory is writable and you have internet connectivity.');
  38. }
  39. if ($checksum && hash_file('sha1', $zipName) !== $checksum) {
  40. throw new \UnexpectedValueException('The checksum verification failed for the '.$package->getName().' archive (downloaded from '.$url.'). Installation aborted.');
  41. }
  42. $zipArchive = new \ZipArchive();
  43. echo 'Unpacking archive'.PHP_EOL;
  44. if (true === ($retval = $zipArchive->open($zipName))) {
  45. $targetPath = $path.'/'.$package->getName();
  46. $zipArchive->extractTo($targetPath);
  47. $zipArchive->close();
  48. echo 'Cleaning up'.PHP_EOL;
  49. unlink($zipName);
  50. if (false !== strpos($url, '//github.com/')) {
  51. $contentDir = glob($targetPath.'/*');
  52. if (1 === count($contentDir)) {
  53. $contentDir = $contentDir[0];
  54. foreach (array_merge(glob($contentDir.'/.*'), glob($contentDir.'/*')) as $file) {
  55. if (trim(basename($file), '.')) {
  56. rename($file, $targetPath.'/'.basename($file));
  57. }
  58. }
  59. rmdir($contentDir);
  60. }
  61. }
  62. } else {
  63. throw new \UnexpectedValueException($zipName.' is not a valid zip archive, got error code '.$retval);
  64. }
  65. }
  66. }