3 namespace Robo\Task\File;
5 use Robo\Contract\CompletionInterface;
8 * Create a temporary file that is automatically cleaned up
9 * once the task collection is is part of completes. When created,
10 * it is given a random filename.
12 * This temporary file may be manipulated exacatly like taskWrite().
13 * It is deleted as soon as the collection it is a part of completes
18 * $collection = $this->collectionBuilder();
19 * $tmpFilePath = $collection->taskTmpFile()
21 * ->line(date('Y-m-d').' '.$title)
28 class TmpFile extends Write implements CompletionInterface
31 * @param string $filename
32 * @param string $extension
33 * @param string $baseDir
34 * @param bool $includeRandomPart
36 public function __construct($filename = 'tmp', $extension = '', $baseDir = '', $includeRandomPart = true)
38 if (empty($baseDir)) {
39 $baseDir = sys_get_temp_dir();
41 if ($includeRandomPart) {
42 $random = static::randomString();
43 $filename = "{$filename}_{$random}";
45 $filename .= $extension;
46 parent::__construct("{$baseDir}/{$filename}");
50 * Generate a suitably random string to use as the suffix for our
57 private static function randomString($length = 12)
59 return substr(str_shuffle('23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'), 0, $length);
63 * Delete this file when our collection completes.
64 * If this temporary file is not part of a collection,
65 * then it will be deleted when the program terminates,
66 * presuming that it was created by taskTmpFile() or _tmpFile().
68 public function complete()
70 unlink($this->getPath());