adlerka.space/lib/script_data.php

28 lines
1.6 KiB
PHP
Raw Permalink Normal View History

2024-02-05 21:21:04 +01:00
<?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 {
2024-02-05 22:52:44 +01:00
// Check if the array is associative and single-level
2024-11-18 19:59:19 +01:00
if (count($phpArray) > 0 && count(array_filter(array_keys($phpArray), 'is_string')) === count($phpArray)) {
2024-02-05 22:52:44 +01:00
// Generate JavaScript code to save each array element to local storage
2024-02-05 22:56:20 +01:00
$out = "<script>";
2024-02-05 22:52:44 +01:00
foreach ($phpArray as $key => $value) {
2024-04-27 11:49:53 +02:00
$escapedKey = addslashes(strval($key)); // Escape special characters in the key
$escapedValue = addslashes(strval($value)); // Escape special characters in the value
2024-02-05 21:21:04 +01:00
2024-02-05 22:56:20 +01:00
$out .= "localStorage.setItem('$escapedKey', '$escapedValue');";
2024-02-05 22:52:44 +01:00
}
2024-02-05 22:56:20 +01:00
$out.= "</script>";
2024-02-05 22:52:44 +01:00
} else {
2024-02-05 22:56:20 +01:00
$out = "<script>console.error('Invalid PHP array. Must be single-level and associative.');</script>";
2024-02-05 22:52:44 +01:00
}
2024-02-05 22:56:20 +01:00
return $out;
2024-02-05 21:21:04 +01:00
}