diff --git a/src/Protection.php b/src/Protection.php index 09c9a6d..69ffefa 100644 --- a/src/Protection.php +++ b/src/Protection.php @@ -12,7 +12,7 @@ class Protection { * within each GLOBAL. For example: ["_ENV" => ["keepThis", "andKeepThis"]] */ public static function removeGlobals( - array &$globalsToDeregister, + array $globalsToDeregister, array $whiteList = [] ):array { $keep = []; @@ -27,14 +27,20 @@ public static function removeGlobals( foreach($keysToKeep as $key) { if(!isset($thisGlobal[$key])) { - continue; + $thisGlobal[$key] = null; } $keep[$globalName][$key] = $thisGlobal[$key]; } } - $globalsToDeregister = $keep; +// This is necessary after PHP 8.1, as it's impossible to pass $GLOBALS by +// reference, and copies of the $GLOBALS array cannot modify the original. + foreach($keep as $key => $kvp) { + foreach($kvp as $k => $value) { + $GLOBALS[$key][$k] = $value; + } + } return $keep; } @@ -56,4 +62,4 @@ public static function overrideInternals( $cookie = new ProtectedGlobal($globals["_COOKIE"] ?? []); $session = new ProtectedGlobal($globals["_SESSION"] ?? []); } -} \ No newline at end of file +} diff --git a/test/phpunit/ProtectionTest.php b/test/phpunit/ProtectionTest.php index f17beea..6c677ce 100644 --- a/test/phpunit/ProtectionTest.php +++ b/test/phpunit/ProtectionTest.php @@ -7,19 +7,6 @@ use PHPUnit\Framework\TestCase; class ProtectionTest extends TestCase { - public function testRemoveGlobals() { - $globals = [ - "_ENV" => [ - "somekey" => "somevalue", - ] - ]; - - self::assertArrayHasKey("somekey", $globals["_ENV"]); - Protection::removeGlobals($globals); - self::assertArrayNotHasKey("_ENV", $globals); - self::assertNotNull($globals); - } - public function testOverride() { $env = ["somekey" => "somevalue"]; $server = []; @@ -137,4 +124,39 @@ public function testWhitelistMany() { self::expectException(ProtectedGlobalException::class); $variable = $post["postkey1"]; } -} \ No newline at end of file + + public function testWhitelistNotExists() { + $env = []; + $server = []; + $get = ["name" => "Cody", "species" => "Feline"]; + $post = []; + $files = []; + $cookie = []; + $session = []; + $globals = [ + "_GET" => $get, + ]; + $globals = Protection::removeGlobals( + $globals, + [ + "_GET" => [ + "name", + "age", + ], + ] + ); + Protection::overrideInternals( + $globals, + $env, + $server, + $get, + $post, + $files, + $cookie, + $session + ); + + self::assertEquals("Cody", $get["name"]); + self::assertNull($get["age"]); + } +}