Page MenuHomeDevCentral

D2499.id.diff
No OneTemporary

D2499.id.diff

diff --git a/src/OS/CurrentProcess.php b/src/OS/CurrentProcess.php
--- a/src/OS/CurrentProcess.php
+++ b/src/OS/CurrentProcess.php
@@ -30,4 +30,30 @@
return posix_geteuid() === 0;
}
+ /**
+ * Determines the username of the current process, ie the PHP interpreter.
+ */
+ public static function getUsername () : string {
+ if (!extension_loaded("posix")) {
+ // POSIX PHP functions aren't always available.
+ // In such cases, `whoami` will probably be available.
+ $username = trim((string)shell_exec("whoami"));
+
+ if (CurrentOS::isWindows() && str_contains('\\', $username)) {
+ // Perhaps the domain information could be useful if the user
+ // can belong to an AD domain, to disambiguate between local
+ // accounts and AD accounts.
+ //
+ // If not attached to a domain, the PC hostname is used.
+ //
+ // We return only the username part to be coherent with UNIX.
+ return explode('\\', $username, 2)[1];
+ }
+
+ return $username;
+ }
+
+ return posix_getpwuid(posix_geteuid())["name"];
+ }
+
}
diff --git a/tests/OS/CurrentProcessTest.php b/tests/OS/CurrentProcessTest.php
new file mode 100644
--- /dev/null
+++ b/tests/OS/CurrentProcessTest.php
@@ -0,0 +1,20 @@
+<?php
+
+namespace Keruald\OmniTools\Tests\OS;
+
+use Keruald\OmniTools\OS\CurrentProcess;
+use PHPUnit\Framework\TestCase;
+
+class CurrentProcessTest extends TestCase {
+
+ // Probably more usernames are valid, but why tests
+ // would run in accounts using spaces or UTF-8 emojis?
+ const USERNAME_REGEXP = "/^([a-zA-Z][a-zA-Z0-9_]*)$/";
+
+ public function testGetUsername () {
+ $actual = CurrentProcess::getUsername();
+
+ $this->assertMatchesRegularExpression(self::USERNAME_REGEXP, $actual);
+ }
+
+}

File Metadata

Mime Type
text/plain
Expires
Sun, Jan 19, 20:49 (17 h, 46 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
2361138
Default Alt Text
D2499.id.diff (1 KB)

Event Timeline