Page MenuHomeDevCentral

D2497.id6289.diff
No OneTemporary

D2497.id6289.diff

diff --git a/src/OS/Environment.php b/src/OS/Environment.php
new file mode 100644
--- /dev/null
+++ b/src/OS/Environment.php
@@ -0,0 +1,29 @@
+<?php
+
+namespace Keruald\OmniTools\OS;
+
+use InvalidArgumentException;
+
+class Environment {
+
+ public static function has (string $key) : bool {
+ return array_key_exists($key, $_ENV)
+ || array_key_exists($key, $_SERVER);
+ }
+
+ /**
+ * @throws InvalidArgumentException
+ */
+ public static function get (string $key) : string {
+ if (!self::has($key)) {
+ throw new InvalidArgumentException("Key not found: $key");
+ }
+
+ return $_ENV[$key] ?? $_SERVER[$key];
+ }
+
+ public static function getOr (string $key, string $default) : string {
+ return $_ENV[$key] ?? $_SERVER[$key] ?? $default;
+ }
+
+}
diff --git a/tests/OS/EnvironmentTest.php b/tests/OS/EnvironmentTest.php
new file mode 100644
--- /dev/null
+++ b/tests/OS/EnvironmentTest.php
@@ -0,0 +1,70 @@
+<?php
+
+namespace Keruald\OmniTools\Tests\OS;
+
+use InvalidArgumentException;
+use Keruald\OmniTools\OS\Environment;
+use PHPUnit\Framework\TestCase;
+
+class EnvironmentTest extends TestCase {
+
+ protected function setUp () : void {
+ // Keep in sync with provideEnvironment data provider
+
+ $_ENV['foo'] = "bar";
+ $_SERVER['foo'] = "baz";
+
+ $_ENV['bar'] = "lorem";
+ $_SERVER['baz'] = "ipsum";
+
+ // And quux isn't defined.
+ }
+
+ public function provideEnvironment () : iterable {
+ yield ["foo", "bar"];
+ yield ["bar", "lorem"];
+ yield ["baz", "ipsum"];
+ }
+
+ public function provideEnvironmentKeys () : iterable {
+ foreach ($this->provideEnvironment() as $kv) {
+ yield [$kv[0]];
+ }
+ }
+
+ /**
+ * @dataProvider provideEnvironmentKeys
+ */
+ public function testHas (string $key) : void {
+ self::assertTrue(Environment::has($key));
+ }
+
+ /**
+ * @dataProvider provideEnvironment
+ */
+ public function testGet (string $key, string $value) : void {
+ self::assertSame($value, Environment::get($key));
+ }
+
+ /**
+ * @dataProvider provideEnvironment
+ */
+ public function testGetOrWhenKeyExists (string $key, string $value) : void {
+ self::assertSame($value, Environment::getOr($key, "default"));
+ }
+
+ public function testHasWhenKeyDoesNotExist () : void {
+ self::assertFalse(Environment::has("quux"));
+ }
+
+
+ public function testGetWhenKeyDoesNotExist () : void {
+ $this->expectException(InvalidArgumentException::class);
+ Environment::get("quux");
+ }
+
+ public function testGetOrWhenKeyDoesNotExist () : void {
+ self::assertSame("default", Environment::getOr("quux", "default"));
+ }
+
+}

File Metadata

Mime Type
text/plain
Expires
Mon, Nov 18, 04:27 (22 h, 24 s)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
2250135
Default Alt Text
D2497.id6289.diff (2 KB)

Event Timeline