TempFile.php
98 lines
| 1 | <?php |
| 2 | namespace Makasim\File; |
| 3 | |
| 4 | /** |
| 5 | * @author Kotlyar Maksim <kotlyar.maksim@gmail.com> |
| 6 | * @since 8/15/12 |
| 7 | */ |
| 8 | class TempFile extends \SplFileInfo |
| 9 | { |
| 10 | /** |
| 11 | * @var array of string paths array(path => path) |
| 12 | */ |
| 13 | protected static $tempFiles = array(); |
| 14 | |
| 15 | /** |
| 16 | * {@inheritdoc} |
| 17 | */ |
| 18 | public function __construct($fileName) |
| 19 | { |
| 20 | parent::__construct($fileName); |
| 21 | |
| 22 | self::registerRemoveTempFilesHandler(); |
| 23 | self::$tempFiles[$fileName] = $fileName; |
| 24 | } |
| 25 | |
| 26 | /** |
| 27 | * Persist file so that it would not be removed at the end of the script execution. |
| 28 | * |
| 29 | * @return \SplFileInfo |
| 30 | */ |
| 31 | public function persist() |
| 32 | { |
| 33 | unset(self::$tempFiles[(string) $this]); |
| 34 | |
| 35 | return $this->getFileInfo(); |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * Creates a temp file with unique filename. |
| 40 | * |
| 41 | * @param string $prefix |
| 42 | * |
| 43 | * @return TempFile |
| 44 | */ |
| 45 | public static function generate($prefix = 'php-tmp-file', $suffix = '') |
| 46 | { |
| 47 | $filename = tempnam(sys_get_temp_dir(), $prefix); |
| 48 | |
| 49 | if ($suffix) { |
| 50 | $i = 0; |
| 51 | do { |
| 52 | $newFilename = $filename . $i++ . $suffix; |
| 53 | } while (file_exists($newFilename)); |
| 54 | |
| 55 | rename($filename, $newFilename); |
| 56 | $filename = $newFilename; |
| 57 | } |
| 58 | |
| 59 | return new static($filename); |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * Creates a temp file from an exist file keeping it safe. |
| 64 | * |
| 65 | * @param mixed $file |
| 66 | * @param string $prefix |
| 67 | * |
| 68 | * @return TempFile |
| 69 | */ |
| 70 | public static function from($file, $prefix = 'php-tmp-file') |
| 71 | { |
| 72 | $tmpFile = static::generate($prefix); |
| 73 | |
| 74 | copy($file, $tmpFile); |
| 75 | |
| 76 | return $tmpFile; |
| 77 | } |
| 78 | |
| 79 | private static function registerRemoveTempFilesHandler() |
| 80 | { |
| 81 | static $registered = false; |
| 82 | if ($registered) { |
| 83 | return; |
| 84 | } |
| 85 | |
| 86 | $tempFiles = &self::$tempFiles; |
| 87 | |
| 88 | register_shutdown_function(function() use (&$tempFiles) { |
| 89 | foreach ($tempFiles as $tempFile) { |
| 90 | if (file_exists($tempFile)) { |
| 91 | @unlink($tempFile); |
| 92 | } |
| 93 | } |
| 94 | }); |
| 95 | |
| 96 | $registered = true; |
| 97 | } |
| 98 | } |