Zip.php 1.9 KB
Newer Older
1 2
<?php

3
namespace Drupal\Core\Archiver;
4 5 6 7 8 9 10 11 12 13 14

/**
 * Defines a archiver implementation for .zip files.
 *
 * @link http://php.net/zip
 */
class Zip implements ArchiverInterface {

  /**
   * The underlying ZipArchive instance that does the heavy lifting.
   *
15
   * @var \ZipArchive
16 17 18 19
   */
  protected $zip;

  /**
20
   * Constructs a Zip object.
21 22
   *
   * @param string $file_path
23 24 25 26
   *   The full system path of the archive to manipulate. Only local files
   *   are supported. If the file does not yet exist, it will be created if
   *   appropriate.
   *
27
   * @throws \Drupal\Core\Archiver\ArchiverException
28 29
   */
  public function __construct($file_path) {
30
    $this->zip = new \ZipArchive();
31
    if ($this->zip->open($file_path) !== TRUE) {
32
      throw new ArchiverException("Cannot open '$file_path'");
33 34 35 36
    }
  }

  /**
37
   * {@inheritdoc}
38 39 40 41 42 43 44 45
   */
  public function add($file_path) {
    $this->zip->addFile($file_path);

    return $this;
  }

  /**
46
   * {@inheritdoc}
47 48 49 50 51 52 53 54
   */
  public function remove($file_path) {
    $this->zip->deleteName($file_path);

    return $this;
  }

  /**
55
   * {@inheritdoc}
56
   */
57
  public function extract($path, array $files = []) {
58 59 60 61 62 63 64 65 66 67 68
    if ($files) {
      $this->zip->extractTo($path, $files);
    }
    else {
      $this->zip->extractTo($path);
    }

    return $this;
  }

  /**
69
   * {@inheritdoc}
70 71
   */
  public function listContents() {
72
    $files = [];
73
    for ($i = 0; $i < $this->zip->numFiles; $i++) {
74 75 76 77 78 79 80 81 82 83 84 85
      $files[] = $this->zip->getNameIndex($i);
    }
    return $files;
  }

  /**
   * Retrieves the zip engine itself.
   *
   * In some cases it may be necessary to directly access the underlying
   * ZipArchive object for implementation-specific logic. This is for advanced
   * use only as it is not shared by other implementations of ArchiveInterface.
   *
86
   * @return \ZipArchive
87 88 89 90 91
   *   The ZipArchive object used by this object.
   */
  public function getArchive() {
    return $this->zip;
  }
92

93
}