Created
September 18, 2012 13:55
-
-
Save makasim/3743251 to your computer and use it in GitHub Desktop.
temp file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Makasim\File; | |
/** | |
* @author Kotlyar Maksim <[email protected]> | |
* @since 8/15/12 | |
*/ | |
class TempFile extends \SplFileInfo | |
{ | |
/** | |
* @var array | |
*/ | |
protected static $tempFiles = array(); | |
/** | |
* {@inheritdoc} | |
*/ | |
public function __construct($fileName) | |
{ | |
self::registerRemoveTempFilesHandler(); | |
self::$tempFiles[$fileName] = $fileName; | |
parent::__construct($fileName); | |
} | |
/** | |
* Persist file so that it would not be removed at the end of the script execution. | |
* | |
* @return \SplFileInfo | |
*/ | |
public function persist() | |
{ | |
unset(self::$tempFiles[$this]); | |
return new \SplFileInfo($this); | |
} | |
/** | |
* Creates a temp file with unique filename. | |
* | |
* @param string $prefix | |
* | |
* @return TempFile | |
*/ | |
public static function generate($prefix = 'php-tmp-file') | |
{ | |
return new static(tempnam(sys_get_temp_dir(), $prefix)); | |
} | |
/** | |
* Creates a temp file from an exist file keeping it safe. | |
* | |
* @param mixed $file | |
* @param string $prefix | |
* | |
* @return TempFile | |
*/ | |
public static function from($file, $prefix = 'php-tmp-file') | |
{ | |
$tmpFile = static::generate($prefix); | |
copy($file, $tmpFile); | |
return $tmpFile; | |
} | |
private static function registerRemoveTempFilesHandler() | |
{ | |
static $registered = false; | |
if ($registered) { | |
return; | |
} | |
$tempFiles = &self::$tempFiles; | |
register_shutdown_function(function() use ($tempFiles) { | |
foreach ($tempFiles as $tempFile) { | |
if (file_exists($tempFile)) { | |
@unlink($tempFile); | |
} | |
} | |
}); | |
$registered = true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment