ZIP::__construct()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 4
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * FileSystem\ZIP
5
 *
6
 * ZIP Archive Filesystem
7
 *
8
 * @package core
9
 * @author [email protected]
10
 * @copyright Caffeina srl - 2015 - http://caffeina.it
11
 */
12
13
namespace FileSystem;
14
15
class ZIP implements Adapter {
16
17
  protected $path,
18
            $zipfile,
19
            $fileCache;
20
21
  public function __construct(array $options = []) {
22
      $this->path    = empty($options['root'])?(tempnam(sys_get_temp_dir(), 'CFZ_').'.zip'):rtrim($options['root']);
23
      $this->zipfile = new \ZipArchive();
24
      if ( !$this->zipfile->open($this->path, \ZipArchive::CREATE) ){
25
          throw new \Exception("File::ZIP Cannot open or create ".$this->path);
26
      }
27
  }
28
29
  public function exists($path){
30
      return false !== $this->zipfile->locateName($path);
31
  }
32
33
  public function read($path){
34
      if (isset($this->fileCache[$path])) return $this->fileCache[$path];
35
      return $this->exists($path) ? $this->zipfile->getFromName($path) : false;
36
  }
37
38
  public function write($path, $data){
39
      // This is needed because we cant write and read from the same archive.
40
      $this->fileCache[$path] = $data;
41
      return $this->zipfile->addFromString($path, $data);
42
  }
43
44
  public function append($path, $data){
45
      return $this->write($path, ($this->read($path) ?: '') . $data);
46
  }
47
48
  public function delete($path){
49
      return $this->exists($path) ? $this->zipfile->deleteName($path) : false;
50
  }
51
52
  public function move($old, $new){
53
      // Atomic rename
54
      // This is needed because we cant write and read from the same archive.
55
      return $this->write($new,$this->read($old)) && $this->delete($old);
56
      // return $this->zipfile->renameName($old, $new);
57
  }
58
59
  public function search($pattern, $recursive=true){
60
      $results = [];
61
      $rx_pattern = '('.strtr($pattern,['.'=>'\.','*'=>'.*','?'=>'.']).')Ai';
62
63
      for( $i = 0, $c = $this->zipfile->numFiles; $i < $c; $i++ ){
64
          $stat = $this->zipfile->statIndex( $i );
65
          if (preg_match($rx_pattern,$stat['name'])) $results[] = $stat['name'];
66
      }
67
68
      return $results;
69
  }
70
71
}
72