Skip to content

Commit 2488218

Browse files
Add method to safely read environment variable
1 parent bf78812 commit 2488218

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/Runner/Util.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,17 @@ public static function getExecType(string $action): string
4747
{
4848
return substr($action, 0, 1) === '\\' ? 'php' : 'cli';
4949
}
50+
51+
/**
52+
* Try to read an environment variable
53+
*
54+
* @param string $name
55+
* @param string $default
56+
* @return string
57+
*/
58+
public static function getEnv(string $name, string $default = ''): string
59+
{
60+
$var = getenv($name);
61+
return $var ?: $_ENV[$name] ?? $_SERVER[$name] ?? $default;
62+
}
5063
}

tests/unit/Runner/UtilTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,4 +46,32 @@ public function testIsTypeValid(): void
4646
$this->assertTrue(Util::isTypeValid('cli'));
4747
$this->assertFalse(Util::isTypeValid('foo'));
4848
}
49+
50+
/**
51+
* Tests Util::getEnv
52+
*/
53+
public function testCanReadEnvVar(): void
54+
{
55+
$_ENV['foo'] = 'bar';
56+
$this->assertEquals('bar', Util::getEnv('foo'));
57+
unset($_ENV['foo']);
58+
}
59+
60+
/**
61+
* Tests Util::getEnv
62+
*/
63+
public function testUsesServerSuperglobalAsFallback(): void
64+
{
65+
$_SERVER['foo'] = 'bar';
66+
$this->assertEquals('bar', Util::getEnv('foo'));
67+
unset($_SERVER['foo']);
68+
}
69+
70+
/**
71+
* Tests Util::getEnv
72+
*/
73+
public function testReturnsDefaultIdEnvNotSet(): void
74+
{
75+
$this->assertEquals('baz', Util::getEnv('fiz', 'baz'));
76+
}
4977
}

0 commit comments

Comments
 (0)