Skip to content

Commit

Permalink
Add addClass() method to Field class for easier class manipulation (#…
Browse files Browse the repository at this point in the history
…2909)

- Implement addClass() method to add classes without overwriting existing ones
- Update class documentation to include new method
- Add unit tests for addClass() method
  • Loading branch information
iamarsenibragimov authored Oct 21, 2024
1 parent 98889b0 commit f4b6bbe
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Screen/Field.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
* @method self style($value = true)
* @method self tabindex($value = true)
* @method self autocomplete($value = true)
* @method self addClass($value = true)
*/
class Field implements Fieldable, Htmlable
{
Expand Down Expand Up @@ -542,4 +543,22 @@ public function toHtml()
{
return $this->render()->toHtml();
}

/**
* Add a class to the field including the existing classes.
*
* @param string|array $classes
*
* @return static
*/
public function addClass(string|array $classes): self
{
$currentClasses = array_filter(explode(' ', $this->get('class', '')));
$newClasses = is_array($classes) ? $classes : explode(' ', $classes);

$mergedClasses = array_unique(array_merge($currentClasses, $newClasses));
$this->set('class', implode(' ', array_filter($mergedClasses)));

return $this;
}
}
40 changes: 40 additions & 0 deletions tests/Unit/FieldTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -217,4 +217,44 @@ public function testNumericOldName(): void

$this->assertSame('3.141', Input::make('numeric')->getOldValue());
}

public function testAddsSingleClassToEmptyClassAttribute(): void
{
$field = Field::make('test');
$field->addClass('new-class');

$this->assertEquals('new-class', $field->get('class'));
}

public function testAddsMultipleClassesToEmptyClassAttribute(): void
{
$field = Field::make('test');
$field->addClass('class1 class2');

$this->assertEquals('class1 class2', $field->get('class'));
}

public function testAddsArrayOfClassesToEmptyClassAttribute(): void
{
$field = Field::make('test');
$field->addClass(['class1', 'class2']);

$this->assertEquals('class1 class2', $field->get('class'));
}

public function testAddsNewClassToExistingClasses(): void
{
$field = Field::make('test')->set('class', 'existing-class');
$field->addClass('new-class');

$this->assertEquals('existing-class new-class', $field->get('class'));
}

public function testDoesNotDuplicateClasses(): void
{
$field = Field::make('test')->set('class', 'existing-class');
$field->addClass('existing-class new-class');

$this->assertEquals('existing-class new-class', $field->get('class'));
}
}

0 comments on commit f4b6bbe

Please sign in to comment.