4a18691d64a204203e126575319b4641088632ef
[yaffs-website] / vendor / consolidation / robo / src / Task / File / TmpFile.php
1 <?php
2
3 namespace Robo\Task\File;
4
5 use Robo\Contract\CompletionInterface;
6
7 /**
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.
11  *
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
14  * or rolls back.
15  *
16  * ``` php
17  * <?php
18  * $collection = $this->collectionBuilder();
19  * $tmpFilePath = $collection->taskTmpFile()
20  *      ->line('-----')
21  *      ->line(date('Y-m-d').' '.$title)
22  *      ->line('----')
23  *      ->getPath();
24  * $collection->run();
25  * ?>
26  * ```
27  */
28 class TmpFile extends Write implements CompletionInterface
29 {
30     /**
31      * @param string $filename
32      * @param string $extension
33      * @param string $baseDir
34      * @param bool $includeRandomPart
35      */
36     public function __construct($filename = 'tmp', $extension = '', $baseDir = '', $includeRandomPart = true)
37     {
38         if (empty($baseDir)) {
39             $baseDir = sys_get_temp_dir();
40         }
41         if ($includeRandomPart) {
42             $random = static::randomString();
43             $filename = "{$filename}_{$random}";
44         }
45         $filename .= $extension;
46         parent::__construct("{$baseDir}/{$filename}");
47     }
48
49     /**
50      * Generate a suitably random string to use as the suffix for our
51      * temporary file.
52      *
53      * @param int $length
54      *
55      * @return string
56      */
57     private static function randomString($length = 12)
58     {
59         return substr(str_shuffle('23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'), 0, $length);
60     }
61
62     /**
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().
67      */
68     public function complete()
69     {
70         unlink($this->getPath());
71     }
72 }