adlerka.top/lib/script_data.php
2024-11-18 19:59:19 +01:00

28 lines
1.6 KiB
PHP

<?php
/**
* Generates a JavaScript script tag containing commands to store PHP array key-value pairs in local storage.
* This function is designed to translate PHP associative array data into JavaScript local storage items.
* It ensures that the array is associative and single-level before proceeding with the JavaScript code generation.
* This is used when dumping session data into local storage for use by the client script.
*
* @param array $phpArray The associative array whose data will be converted into JavaScript local storage setItem calls.
* @return string Returns a script tag with JavaScript code. If the input is not a valid single-level associative array,
* it returns a script with an error logged to the console.
*/
function generateScriptData(array $phpArray):string {
// Check if the array is associative and single-level
if (count($phpArray) > 0 && count(array_filter(array_keys($phpArray), 'is_string')) === count($phpArray)) {
// Generate JavaScript code to save each array element to local storage
$out = "<script>";
foreach ($phpArray as $key => $value) {
$escapedKey = addslashes(strval($key)); // Escape special characters in the key
$escapedValue = addslashes(strval($value)); // Escape special characters in the value
$out .= "localStorage.setItem('$escapedKey', '$escapedValue');";
}
$out.= "</script>";
} else {
$out = "<script>console.error('Invalid PHP array. Must be single-level and associative.');</script>";
}
return $out;
}