Skip to content

Commit

Permalink
Prevent empty id attribute (#143)
Browse files Browse the repository at this point in the history
  • Loading branch information
mjauvin authored Mar 1, 2023
1 parent 642260e commit 13bffb8
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Html/FormBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,10 @@ public function input(string $type, ?string $name = null, ?string $value = null,
// when creating the HTML element. Then, we will return the entire input.
$merge = compact('type', 'value', 'id');

if ($id === "") {
unset($merge['id']);
}

$options = array_filter(array_merge($options, $merge), function ($item) {
return !is_null($item);
});
Expand Down
58 changes: 58 additions & 0 deletions tests/Html/FormBuilderTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

use Winter\Storm\Html\HtmlBuilder;
use Winter\Storm\Html\FormBuilder;
use Winter\Storm\Router\UrlGenerator;

use Illuminate\Http\Request;
use Illuminate\Routing\RouteCollection;

class FormBuilderTest extends TestCase
{
public function setUp() : void
{
$htmlBuilder = new HtmlBuilder;
$generator = new UrlGenerator(
new RouteCollection,
Request::create('https://www.example.com/path/?query=arg#fragment')
);
$this->formBuilder = new FormBuilder($htmlBuilder, $generator);
}

public function testInputIdMissing()
{
$result = $this->formBuilder->input(type:"text", name:"my-name", value:"my value");
$this->assertEquals('<input name="my-name" type="text" value="my value">', $result);
}

public function testInputIdEmpty()
{
$result = $this->formBuilder->input(type:"text", name:"my-name", value:"my value", options:["id"=>""]);
$this->assertEquals('<input id="" name="my-name" type="text" value="my value">', $result);
}

public function testInputIdNull()
{
$result = $this->formBuilder->input(type:"text", name:"my-name", value:"my value", options:["id"=>null]);
$this->assertEquals('<input name="my-name" type="text" value="my value">', $result);
}

public function testInputIdFalse()
{
$result = $this->formBuilder->input(type:"text", name:"my-name", value:"my value", options:["id"=>false]);
$this->assertEquals('<input id="" name="my-name" type="text" value="my value">', $result);
}

public function testInputIdZero()
{
$result = $this->formBuilder->input(type:"text", name:"my-name", value:"my value", options:["id"=>0]);
$this->assertEquals('<input id="0" name="my-name" type="text" value="my value">', $result);
}

public function testInputIdMissingWithAssociatedLabel()
{
$result = $this->formBuilder->label(name:"my-input", value:"my input label");
$result = $this->formBuilder->input(type:"text", name:"my-input", value:"my value");
$this->assertEquals('<input name="my-input" type="text" value="my value" id="my-input">', $result);
}
}

0 comments on commit 13bffb8

Please sign in to comment.