Skip to content

Commit

Permalink
feature: whitelisted variables return null if not set (#145)
Browse files Browse the repository at this point in the history
* maintenance: no need to pass GLOBALS by reference

* feature: whitelisted variables return null if not set
closes #144
  • Loading branch information
g105b authored Sep 22, 2022
1 parent 9a9c550 commit 4e909c4
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 18 deletions.
14 changes: 10 additions & 4 deletions src/Protection.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [];
Expand All @@ -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;
}

Expand All @@ -56,4 +62,4 @@ public static function overrideInternals(
$cookie = new ProtectedGlobal($globals["_COOKIE"] ?? []);
$session = new ProtectedGlobal($globals["_SESSION"] ?? []);
}
}
}
50 changes: 36 additions & 14 deletions test/phpunit/ProtectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [];
Expand Down Expand Up @@ -137,4 +124,39 @@ public function testWhitelistMany() {
self::expectException(ProtectedGlobalException::class);
$variable = $post["postkey1"];
}
}

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"]);
}
}

0 comments on commit 4e909c4

Please sign in to comment.