use additional file_exists checks
[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 if (is_file($this->getPathname())) {
41 @unlink($this->getPathname());
42 }
43 }
44
45 /**
46 * Close the stream
47 */
48 public function closeStream() {
49 fclose($this->handle);
50 }
51
52 /**
53 * Retrieve the stream resource
54 * @return resource
55 */
56 public function getStream() {
57 return $this->handle;
58 }
59 }