Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Zip.php
Go to the documentation of this file.
1 <?php
8 
12 class Zip extends AbstractArchive implements ArchiveInterface
13 {
17  public function __construct()
18  {
19  $type = 'Zip';
20  if (!class_exists('\ZipArchive')) {
21  throw new \Magento\Framework\Exception\LocalizedException(
22  new \Magento\Framework\Phrase('\'%1\' file extension is not supported', [$type])
23  );
24  }
25  }
26 
35  public function pack($source, $destination)
36  {
37  $zip = new \ZipArchive();
38  $zip->open($destination, \ZipArchive::CREATE);
39  $zip->addFile($source);
40  $zip->close();
41  return $destination;
42  }
43 
52  public function unpack($source, $destination)
53  {
54  $zip = new \ZipArchive();
55  if ($zip->open($source) === true) {
56  $filename = $this->filterRelativePaths($zip->getNameIndex(0) ?: '');
57  if ($filename) {
58  $zip->extractTo(dirname($destination), $filename);
59  rename(dirname($destination).'/'.$filename, $destination);
60  } else {
61  $destination = '';
62  }
63  $zip->close();
64  } else {
65  $destination = '';
66  }
67 
68  return $destination;
69  }
70 
77  private function filterRelativePaths(string $path): string
78  {
79  if ($path && preg_match('#^\s*(../)|(/../)#i', $path)) {
80  $path = '';
81  }
82 
83  return $path;
84  }
85 }
pack($source, $destination)
Definition: Zip.php:35
$source
Definition: source.php:23
$type
Definition: item.phtml:13
unpack($source, $destination)
Definition: Zip.php:52