Skip to content

Commit 0ea16fa

Browse files
committed
gracefully handle invalid session data
1 parent 77509e2 commit 0ea16fa

File tree

1 file changed

+27
-12
lines changed

1 file changed

+27
-12
lines changed

resources/lib/UnityHTTPD.php

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -209,8 +209,33 @@ public static function alert(string $message): void
209209
echo "<script type='text/javascript'>alert(" . \jsonEncode($message) . ");</script>";
210210
}
211211

212+
private static function ensureSessionMessagesSanity()
213+
{
214+
if (!isset($_SESSION)) {
215+
throw new RuntimeException('$_SESSION is unset');
216+
}
217+
if (!array_key_exists("messages", $_SESSION)) {
218+
self::errorLog(
219+
"invalid session messages",
220+
'array key "messages" does not exist for $_SESSION',
221+
data: ['$_SESSION' => $_SESSION],
222+
);
223+
$_SESSION["messages"] = [];
224+
}
225+
if (!is_array($_SESSION["messages"])) {
226+
$type = gettype($_SESSION["messages"]);
227+
self::errorLog(
228+
"invalid session messages",
229+
"\$_SESSION['messages'] is type '$type', not an array",
230+
data: ['$_SESSION' => $_SESSION],
231+
);
232+
$_SESSION["messages"] = [];
233+
}
234+
}
235+
212236
public static function message(string $title, string $body, UnityHTTPDMessageLevel $level)
213237
{
238+
self::ensureSessionMessagesSanity();
214239
array_push($_SESSION["messages"], [$title, $body, $level]);
215240
}
216241

@@ -237,18 +262,8 @@ public static function messageError(string $title, string $body)
237262

238263
public static function getMessages()
239264
{
240-
if (!isset($_SESSION)) {
241-
throw new RuntimeException('$_SESSION is unset');
242-
}
243-
if (!array_key_exists("messages", $_SESSION)) {
244-
throw new RuntimeException('array key "messages" does not exist for $_SESSION');
245-
}
246-
$messages = $_SESSION["messages"];
247-
if (!is_array($messages)) {
248-
$type = gettype($messages);
249-
throw new RuntimeException("\$_SESSION['messages'] is type '$type', not an array");
250-
}
251-
return $messages;
265+
self::ensureSessionMessagesSanity();
266+
return $_SESSION["messages"];
252267
}
253268

254269
public static function clearMessages()

0 commit comments

Comments
 (0)