ZipArchiver.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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\Package\Archiver;
  12. use ZipArchive;
  13. /**
  14. * @author Jan Prieser <jan@prieser.net>
  15. */
  16. class ZipArchiver implements ArchiverInterface
  17. {
  18. protected static $formats = array(
  19. 'zip' => 1
  20. );
  21. /**
  22. * {@inheritdoc}
  23. */
  24. public function archive($sources, $target, $format, array $excludes = array())
  25. {
  26. $sources = realpath($sources);
  27. $zip = new ZipArchive();
  28. $res = $zip->open($target, ZipArchive::CREATE);
  29. if ($res === true) {
  30. $files = new ArchivableFilesFinder($sources, $excludes);
  31. foreach($files as $file) {
  32. /** @var $file \SplFileInfo */
  33. $filepath = $file->getPath()."/".$file->getFilename();
  34. $localname = str_replace($sources."/", '', $filepath);
  35. $zip->addFile($filepath, $localname);
  36. }
  37. if ($zip->close()) {
  38. return $target;
  39. }
  40. }
  41. $message = sprintf("Could not create archive '%s' from '%s': %s",
  42. $target,
  43. $sources,
  44. $zip->getStatusString()
  45. );
  46. throw new \RuntimeException($message);
  47. }
  48. /**
  49. * {@inheritdoc}
  50. */
  51. public function supports($format, $sourceType)
  52. {
  53. return isset(static::$formats[$format]) && $this->compressionAvailable();
  54. }
  55. private function compressionAvailable() {
  56. return class_exists('ZipArchive');
  57. }
  58. }