Skip to content

Commit

Permalink
[5.x] filter modifier (#10962)
Browse files Browse the repository at this point in the history
Co-authored-by: Jason Varga <[email protected]>
  • Loading branch information
marcorieser and jasonvarga authored Oct 16, 2024
1 parent d6c6395 commit 9745141
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/Modifiers/CoreModifiers.php
Original file line number Diff line number Diff line change
Expand Up @@ -710,6 +710,19 @@ public function favicon($value)
return Html::favicon($value);
}

/**
* Filters out empty values from an array or collection.
*
* @param array $value
* @return array
*/
public function filterEmpty($value)
{
return collect($value)
->filter()
->when(is_array($value), fn ($collection) => $collection->all());
}

/**
* Returns the first $params[0] characters of a string, or the first element of an array.
*
Expand Down
31 changes: 31 additions & 0 deletions tests/Modifiers/FilterEmptyTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace Tests\Modifiers;

use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\Test;
use Statamic\Modifiers\Modify;
use Tests\TestCase;

#[Group('array')]
class FilterEmptyTest extends TestCase
{
#[Test]
public function it_removes_null_values_from_an_array(): void
{
$modified = $this->modify(['one' => 'one', null, 'two' => 'two', 'three' => null, 'four' => 'four']);
$this->assertEquals(['one' => 'one', 'two' => 'two', 'four' => 'four'], $modified);
}

#[Test]
public function it_removes_null_values_from_a_collection(): void
{
$modified = $this->modify(collect(['one' => 'one', null, 'two' => 'two', 'three' => null, 'four' => 'four']));
$this->assertEquals(['one' => 'one', 'two' => 'two', 'four' => 'four'], $modified->all());
}

private function modify($value, $params = [])
{
return Modify::value($value)->filterEmpty($params)->fetch();
}
}

0 comments on commit 9745141

Please sign in to comment.