Zip.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace Drupal\Core\Archiver;
  3. /**
  4. * Defines a archiver implementation for .zip files.
  5. *
  6. * @link http://php.net/zip
  7. */
  8. class Zip implements ArchiverInterface {
  9. /**
  10. * The underlying ZipArchive instance that does the heavy lifting.
  11. *
  12. * @var \ZipArchive
  13. */
  14. protected $zip;
  15. /**
  16. * Constructs a Zip object.
  17. *
  18. * @param string $file_path
  19. * The full system path of the archive to manipulate. Only local files
  20. * are supported. If the file does not yet exist, it will be created if
  21. * appropriate.
  22. *
  23. * @throws \Drupal\Core\Archiver\ArchiverException
  24. */
  25. public function __construct($file_path) {
  26. $this->zip = new \ZipArchive();
  27. if ($this->zip->open($file_path) !== TRUE) {
  28. throw new ArchiverException(t('Cannot open %file_path', ['%file_path' => $file_path]));
  29. }
  30. }
  31. /**
  32. * {@inheritdoc}
  33. */
  34. public function add($file_path) {
  35. $this->zip->addFile($file_path);
  36. return $this;
  37. }
  38. /**
  39. * {@inheritdoc}
  40. */
  41. public function remove($file_path) {
  42. $this->zip->deleteName($file_path);
  43. return $this;
  44. }
  45. /**
  46. * {@inheritdoc}
  47. */
  48. public function extract($path, array $files = []) {
  49. if ($files) {
  50. $this->zip->extractTo($path, $files);
  51. }
  52. else {
  53. $this->zip->extractTo($path);
  54. }
  55. return $this;
  56. }
  57. /**
  58. * {@inheritdoc}
  59. */
  60. public function listContents() {
  61. $files = [];
  62. for ($i = 0; $i < $this->zip->numFiles; $i++) {
  63. $files[] = $this->zip->getNameIndex($i);
  64. }
  65. return $files;
  66. }
  67. /**
  68. * Retrieves the zip engine itself.
  69. *
  70. * In some cases it may be necessary to directly access the underlying
  71. * ZipArchive object for implementation-specific logic. This is for advanced
  72. * use only as it is not shared by other implementations of ArchiveInterface.
  73. *
  74. * @return \ZipArchive
  75. * The ZipArchive object used by this object.
  76. */
  77. public function getArchive() {
  78. return $this->zip;
  79. }
  80. }