e7205519ea784869a58c821d132609091a4720c3
[pharext/pharext] / src / pharext / Tempfile.php
1 <?php
2
3 namespace pharext;
4
5 /**
6 * Create a new temporary file
7 */
8 class Tempfile extends \SplFileInfo
9 {
10 /**
11 * @var resource
12 */
13 private $handle;
14
15 /**
16 * @param string $prefix uniqid() prefix
17 * @param string $suffix e.g. file extension
18 * @throws \pharext\Exception
19 */
20 public function __construct($prefix, $suffix = ".tmp") {
21 $tries = 0;
22 $omask = umask(077);
23 do {
24 $path = new Tempname($prefix, $suffix);
25 $this->handle = fopen($path, "x");
26 } while (!is_resource($this->handle) && $tries++ < 10);
27 umask($omask);
28
29 if (!is_resource($this->handle)) {
30 throw new Exception("Could not create temporary file");
31 }
32
33 parent::__construct($path);
34 }
35
36 /**
37 * Unlink the file
38 */
39 public function __destruct() {
40 @unlink($this->getPathname());
41 }
42
43 /**
44 * Close the stream
45 */
46 public function closeStream() {
47 fclose($this->handle);
48 }
49
50 /**
51 * Retrieve the stream resource
52 * @return resource
53 */
54 public function getStream() {
55 return $this->handle;
56 }
57 }