lnear-dev/html

Boolean Attributes

Closed this issue · 2 comments

I'm having a problem with checking radio buttons and checkboxes, or to be precise I am having problems not checking it, take a look at the examples below (I am assuming this is the case for all boolean attributes):

Unchecked Input Box

<?=html\input(
    type: 'checkbox',
    id: 'customer_id',
    name: 'customer_id',
    value: '1',
    checked: false,
) ?>

Expected Result

<input type='checkbox' id='customer_id' name='customer_id' value='1'/>

Actual Result

<input type='checkbox' id='customer_id' name='customer_id' value='1' checked=''/>

Checked Input Box

<?=html\input(
    type: 'checkbox',
    id: 'customer_id',
    name: 'customer_id',
    value: '1',
    checked: true,
) ?>

Expected Result

<input type='checkbox' id='customer_id' name='customer_id' value='1' checked/>

Actual Result

<input type='checkbox' id='customer_id' name='customer_id' value='1' checked='1'/>

I would suggest something like the following in /src/Renderer.php to fix:

public static function attributes(string|bool ...$attributes): string
    {
        $attrs = '';
        foreach ($attributes as $key => $value) {
            $key = htmlspecialchars(
                preg_replace_callback(
                    '/[A-Z]/',
                    fn($match) => '-' . strtolower($match[0]),
                    $key,
                ),
            );

            if (is_array($value)) {
                $value = implode(' ', $value);
            }
            
            if($value === true)
            {
                $attrs .= " {$key}";
            }
            else if( $value !== false )
            {
                 $value = htmlspecialchars($value);
                 $attrs .= " {$key}='{$value}'";
            }
        }

        return $attrs;
    }