ZIP   A
last analyzed

Complexity

Total Complexity 18

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 0
loc 74
rs 10
c 0
b 0
f 0
wmc 18
lcom 1
cbo 1

8 Methods

Rating   Name   Duplication   Size   Complexity  
A create() 0 3 1
A __construct() 0 11 5
A __destruct() 0 3 1
A path() 0 3 1
A write() 0 4 1
A close() 0 4 2
A addDirectory() 0 17 5
A download() 0 13 2
1
<?php
2
3
/**
4
 * ZIP
5
 *
6
 * Archive compressed data.
7
 *
8
 * @package core
9
 * @author [email protected]
10
 * @copyright Caffeina srl - 2015 - http://caffeina.it
11
 */
12
13
class ZIP {
14
  use Module;
15
16
  public $file,
17
         $name,
18
         $zip;
19
20
  public static function create($name=''){
21
    return new ZIP($name);
22
  }
23
24
  public function __construct($name=''){
25
    $this->name = preg_replace('/\.zip$/','',($name?:tempnam(sys_get_temp_dir(), 'ZExp').'-archive'));
26
    $this->file = $this->name . '.zip';
27
    if (!preg_match('~^/|\./|\.\./~',$this->file)) $this->file = './'.$this->file;
28
    $this->zip  = new \ZipArchive;
29
    if ( true !== ($e = $this->zip->open($this->file,
30
      \ZipArchive::CREATE || \ZipArchive::OVERWRITE
31
    ))) {
32
      throw new Exception("Error opening temp ZIP file [".($this->file)."] Code $e", 1);
33
    }
34
  }
35
36
  public function __destruct(){
37
    $this->close();
38
  }
39
40
  public function path(){
41
    return $this->file;
42
  }
43
44
  public function write($filename, $data){
45
    $this->zip->addFromString($filename, $data);
46
    return $this;
47
  }
48
49
  public function close(){
50
    if($this->zip) @$this->zip->close();
51
    return $this;
52
  }
53
54
  public function addDirectory($folder, $root=null) {
55
    $folder = rtrim($folder,'/');
56
    if (null === $root) {
57
      $root   = dirname($folder);
58
      $folder = basename($folder);
59
    }
60
    $this->zip->addEmptyDir($folder);
61
    foreach (glob("$root/$folder/*") as $item) {
62
      if (is_dir($item)) {
63
          $this->addDirectory(str_replace($root,'',$item),$root);
64
      } else if (is_file($item))  {
65
          $this->zip->addFile($item, str_replace($root,'',$item));
66
      }
67
    }
68
69
    return $this;
70
  }
71
72
  public function download(){
73
    @$this->zip->close();
74
    header('Content-Type: application/zip');
75
    header('Content-Disposition: attachment;filename="'.$this->name.'"',true);
76
    header('Content-Transfer-Encoding: binary');
77
    header('Expires: 0');
78
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
79
    header('Pragma: public');
80
    header('Content-Length: '.filesize($this->file));
81
    while(ob_get_level()) ob_end_clean();
82
    readfile($this->file);
83
    exit;
84
  }
85
86
}
87