PageRenderTime 34ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Composer/Package/Archiver/PharArchiver.php

http://github.com/composer/composer
PHP | 97 lines | 54 code | 16 blank | 27 comment | 4 complexity | f15c45b21e6c1d409b1196edfe0c9d8a MD5 | raw file
  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. /**
  13. * @author Till Klampaeckel <till@php.net>
  14. * @author Nils Adermann <naderman@naderman.de>
  15. * @author Matthieu Moquet <matthieu@moquet.net>
  16. */
  17. class PharArchiver implements ArchiverInterface
  18. {
  19. protected static $formats = array(
  20. 'zip' => \Phar::ZIP,
  21. 'tar' => \Phar::TAR,
  22. 'tar.gz' => \Phar::TAR,
  23. 'tar.bz2' => \Phar::TAR,
  24. );
  25. protected static $compressFormats = array(
  26. 'tar.gz' => \Phar::GZ,
  27. 'tar.bz2' => \Phar::BZ2,
  28. );
  29. /**
  30. * {@inheritdoc}
  31. */
  32. public function archive($sources, $target, $format, array $excludes = array(), $ignoreFilters = false)
  33. {
  34. $sources = realpath($sources);
  35. // Phar would otherwise load the file which we don't want
  36. if (file_exists($target)) {
  37. unlink($target);
  38. }
  39. try {
  40. $filename = substr($target, 0, strrpos($target, $format) - 1);
  41. // Check if compress format
  42. if (isset(static::$compressFormats[$format])) {
  43. // Current compress format supported base on tar
  44. $target = $filename . '.tar';
  45. }
  46. $phar = new \PharData($target, null, null, static::$formats[$format]);
  47. $files = new ArchivableFilesFinder($sources, $excludes, $ignoreFilters);
  48. $filesOnly = new ArchivableFilesFilter($files);
  49. $phar->buildFromIterator($filesOnly, $sources);
  50. $filesOnly->addEmptyDir($phar, $sources);
  51. if (isset(static::$compressFormats[$format])) {
  52. // Check can be compressed?
  53. if (!$phar->canCompress(static::$compressFormats[$format])) {
  54. throw new \RuntimeException(sprintf('Can not compress to %s format', $format));
  55. }
  56. // Delete old tar
  57. unlink($target);
  58. // Compress the new tar
  59. $phar->compress(static::$compressFormats[$format]);
  60. // Make the correct filename
  61. $target = $filename . '.' . $format;
  62. }
  63. return $target;
  64. } catch (\UnexpectedValueException $e) {
  65. $message = sprintf(
  66. "Could not create archive '%s' from '%s': %s",
  67. $target,
  68. $sources,
  69. $e->getMessage()
  70. );
  71. throw new \RuntimeException($message, $e->getCode(), $e);
  72. }
  73. }
  74. /**
  75. * {@inheritdoc}
  76. */
  77. public function supports($format, $sourceType)
  78. {
  79. return isset(static::$formats[$format]);
  80. }
  81. }