trongate / trongate-framework

The Trongate PHP framework
https://trongate.io
Other
1.12k stars 100 forks source link

change out method to accept empty string or null values without an error #167

Closed mjim closed 6 months ago

mjim commented 8 months ago

I get this error when my value is null:

Got error 'PHP message: PHP Fatal error: Uncaught TypeError: out(): Argument #1 ($input) must be of type string, null given

I suggest making these changes in string_helper.php to the out method to accept a null value or empty string without creating an error:

function out(?string $input = '', string $encoding = 'UTF-8', string $output_format = 'html'): string {
    if ($input === null) {
        $input = '';
    }
DaFa66 commented 8 months ago

Hi Jim, If you are using VSCode and have a PHP code linter installed, you should be seeing a red squiggly underline on the variable you are passing to out($some_variable_that_might_be_null), however, I think your suggestion is good and will avoid that nasty fatal TypeError message. If you can, please create a pull request so DC may consider your suggestion.

    function test_out() {
        $x = null;
        $y = out($x);
        echo $x . '<br>' . $y;
    }
/**
 * Safely escape and format a string for various output contexts.
 *
 * @param string $input The string to be escaped.
 * @param string $encoding (Optional) The character encoding to use for escaping. Defaults to 'UTF-8'.
 * @param string $output_format (Optional) The desired output format: 'html' (default), 'xml', 'json', 'javascript', or 'attribute'.
 * 
 * @return string The escaped and formatted string ready for safe inclusion in the specified context.
 * @throws Exception if an unsupported output format is provided.
 */
function out(?string $input, string $encoding = 'UTF-8', string $output_format = 'html'): string {
    $flags = ENT_QUOTES;

    if ($input === null) {
        $input = '';
    }

    if ($output_format === 'xml') {
        $flags = ENT_XML1;
    } elseif ($output_format === 'json') {
        // Customize JSON escaping as needed
        $input = json_encode($input, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
        $flags = ENT_NOQUOTES;
    } elseif ($output_format === 'javascript') {
        // JavaScript-encode the input
        $input = json_encode($input, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
    } elseif ($output_format === 'attribute') {
        // Escape for HTML attributes
        $flags = ENT_QUOTES;
    } else {
        // Dynamically choose the right function
        $input = ($output_format === 'html') ? htmlspecialchars($input, $flags, $encoding) : htmlentities($input, $flags, $encoding);
        return $input;
    }

    return htmlspecialchars($input, $flags, $encoding);
}
trongate commented 6 months ago

A pull request came in today (thank you Jim!). May I assume that this is resolved?

mjim commented 6 months ago

Yes, thank you!