Skip to content

Instantly share code, notes, and snippets.

@barryhughes
Last active August 29, 2015 14:07
Show Gist options
  • Save barryhughes/52a58d23bbe58f4e049b to your computer and use it in GitHub Desktop.
Save barryhughes/52a58d23bbe58f4e049b to your computer and use it in GitHub Desktop.
Write a string to a temp file, gunzip it, clean up the temp files and return the decompressed string
<?php
use Exception,
Zend\Filter\Decompress;
/**
* The gzip adapter for Zend's decompression filter doesn't always
* operate reliably on strings. This utility class transparently writes
* the string to a temp file and then passes it through the filter.
*
* The uncompressed result is then available through the get_string()
* method, or is instantly available through static method get().
*
* Usage (#1):
*
* $unzipped_content = GunzipString::get($zipped_content);
*
* Usage (#2):
*
* $unzipper = new GunzipString($zipped_content);
* $unzipped_content = $unzipper->get_string();
*
* @see http://framework.zend.com/manual/2.3/en/modules/zend.filter.set.html#compress-and-decompress
*/
class GunzipString
{
protected $string = '';
protected $success = false;
protected $tmp_src = '';
protected $tmp_tgt = '';
public static function get($string) {
$unzip = new self($string);
return $unzip->get_string();
}
public function __construct($string) {
$this->success = ($this->create_temp_file($string) && $this->decompress());
}
protected function create_temp_file($string) {
$this->tmp_src = tempnam(sys_get_temp_dir(), 'scanwp');
$this->tmp_tgt = tempnam(sys_get_temp_dir(), 'scanwp');
return ( $this->tmp_src && file_put_contents($this->tmp_src, $string));
}
protected function decompress() {
try {
$this->do_decompression();
$this->do_cleanup();
return true;
}
catch (Exception $e) {
return false;
}
}
protected function do_decompression() {
$filter = new Decompress([
'adapter' => 'gz',
'options' => [
'archive' => $this->tmp_src,
'target' => $this->tmp_tgt
]
]);
$this->string = $filter->filter($this->tmp_src);
}
protected function do_cleanup() {
unlink($this->tmp_src);
unlink($this->tmp_tgt);
}
public function was_successful() {
return $this->success;
}
public function get_string() {
return $this->string;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment