在调用close()之后,有什么方法可以比较ZipArchive对象吗?

时间:2019-01-17 18:26:33

标签: php

在编写一些单元测试时,我偶然发现了一个非常困难的问题。

简化方案:

  1. Zip存档已创建。
  2. 它是用ZipArchive::addFromString()方法填充的。
  3. 那是封闭的。
  4. ZipArchive::open()中使用的文件名未知。

代码示例

function zipUp() {
    $zip = new ZipArchive();
    $zip->open(rand() . '.zip', ZipArchive::CREATE);
    $zip->addFromString('test.txt', 'success');
    $zip->close();

    return $zip;
}

$zip1 = zipUp();
$zip2 = zipUp();

// TODO: Compare the archives

问题

比较zip存档的内容。比较方法可以使用类似于ZipArchive::statIndex()的东西。

理想情况下,无需任何访问文件系统,仅从内存中读取zip数据。

1 个答案:

答案 0 :(得分:0)

基于评论。

  

在这种特殊情况下,我不知道存档的文件名(不要问为什么),我只有ZipArchive的一个实例

我会尝试这样的事情:

class MyZipArchive extends ZipArchive{

    protected $filename;

    #override open
    public function open($filename, $flags=null){
        #store the filename
        $this->filename = $filename;
        return parent::open($filename,$flags);
    }

    public function getFilename(){
        return $this->filename;
    }

    public function getFileHash(){
        return md5_file($this->filename);
    }
}

然后在您的代码中:

function zipUp() {
    $zip = new MyZipArchive();
    $zip->open(rand() . '.zip', ZipArchive::CREATE);
    $zip->addFromString('test.txt', 'success');
    $zip->close();

    return $zip;
}

$zip1 = zipUp();
$zip2 = zipUp();

if($zip1->getFileHash() == $zip2->getFileHash()){
       //do something
}