Zip.php 1.98 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Magento\Framework\Archive;

/**
 * Zip compressed file archive.
 */
class Zip extends AbstractArchive implements ArchiveInterface
{
    /**
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function __construct()
    {
        $type = 'Zip';
        if (!class_exists('\ZipArchive')) {
            throw new \Magento\Framework\Exception\LocalizedException(
                new \Magento\Framework\Phrase('\'%1\' file extension is not supported', [$type])
            );
        }
    }

    /**
     * Pack file.
     *
     * @param string $source
     * @param string $destination
     *
     * @return string
     */
    public function pack($source, $destination)
    {
        $zip = new \ZipArchive();
        $zip->open($destination, \ZipArchive::CREATE);
        $zip->addFile($source);
        $zip->close();
        return $destination;
    }

    /**
     * Unpack file.
     *
     * @param string $source
     * @param string $destination
     *
     * @return string
     */
    public function unpack($source, $destination)
    {
        $zip = new \ZipArchive();
        if ($zip->open($source) === true) {
            $filename = $this->filterRelativePaths($zip->getNameIndex(0) ?: '');
            if ($filename) {
                $zip->extractTo(dirname($destination), $filename);
                rename(dirname($destination).'/'.$filename, $destination);
            } else {
                $destination = '';
            }
            $zip->close();
        } else {
            $destination = '';
        }

        return $destination;
    }

    /**
     * Filter file names with relative paths.
     *
     * @param string $path
     * @return string
     */
    private function filterRelativePaths(string $path): string
    {
        if ($path && preg_match('#^\s*(../)|(/../)#i', $path)) {
            $path = '';
        }

        return $path;
    }
}