remove hard dependency on ext/posix
[pharext/pharext] / src / pharext / Tempname.php
1 <?php
2
3 namespace pharext;
4
5 use pharext\Exception;
6
7 /**
8 * A temporary file/directory name
9 */
10 class Tempname
11 {
12 /**
13 * @var string
14 */
15 private $name;
16
17 /**
18 * @param string $prefix uniqid() prefix
19 * @param string $suffix e.g. file extension
20 */
21 public function __construct($prefix, $suffix = null) {
22 $temp = sys_get_temp_dir() . "/pharext-" . $this->getUser();
23 if (!is_dir($temp) && !mkdir($temp, 0700, true)) {
24 throw new Exception;
25 }
26 $this->name = $temp ."/". uniqid($prefix) . $suffix;
27 }
28
29 private function getUser() {
30 if (extension_loaded("posix") && function_exists("posix_getpwuid")) {
31 return posix_getpwuid(posix_getuid())["name"];
32 }
33 return trim(`whoami 2>/dev/null`)
34 ?: trim(`id -nu 2>/dev/null`)
35 ?: getenv("USER")
36 ?: get_current_user();
37 }
38
39 /**
40 * @return string
41 */
42 public function __toString() {
43 return (string) $this->name;
44 }
45 }