Skip to content

Commit

Permalink
Add new "find" filter
Browse files Browse the repository at this point in the history
This filter returns the first _value_ matching the given arrow function or null

Attempt to solve #3962

(open to any feedback)
  • Loading branch information
smnandre committed Jan 26, 2024
1 parent 594c548 commit 1daf5b5
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/Extension/CoreExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,7 @@ public function getFilters(): array
new TwigFilter('filter', [self::class, 'arrayFilter'], ['needs_environment' => true]),
new TwigFilter('map', [self::class, 'arrayMap'], ['needs_environment' => true]),
new TwigFilter('reduce', [self::class, 'arrayReduce'], ['needs_environment' => true]),
new TwigFilter('find', [self::class, 'arrayFind'], ['needs_environment' => true]),

// string/array filters
new TwigFilter('reverse', [self::class, 'reverseFilter'], ['needs_environment' => true]),
Expand Down Expand Up @@ -1769,6 +1770,22 @@ public static function arrayFilter(Environment $env, $array, $arrow)
return new \CallbackFilterIterator(new \IteratorIterator($array), $arrow);
}

/**
* @internal
*/
public static function arrayFind(Environment $env, $array, $arrow)
{
self::checkArrowInSandbox($env, $arrow, 'find', 'filter');

foreach ($array as $k => $v) {
if ($arrow($v, $k)) {
return $v;
}
}

return null;
}

/**
* @internal
*/
Expand Down
46 changes: 46 additions & 0 deletions tests/Fixtures/filters/find.test
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
--TEST--
"filter" filter
--TEMPLATE--

{{ [1, 2]|find((v) => v > 3) }}

{{ [1, 5, 3, 4, 5]|find((v) => v > 3) }}

{{ [1, 5, 3, 4, 5]|find((v) => v > 3) }}

{{ {a: 1, b: 2, c: 5, d: 8}|find(v => v > 3) }}

{{ {a: 1, b: 2, c: 5, d: 8}|find((v, k) => (v > 3) and (k != "c")) }}

{{ [1, 5, 3, 4, 5]|find(v => v > 3) }}

{{ it|find((v) => v > 3) }}

{{ ita|find(v => v > 3) }}

{{ xml|find(x => true) }}

--DATA--
return [
'it' => new \ArrayIterator(['a' => 1, 'b' => 2, 'c' => 5, 'd' => 8]),
'ita' => new Twig\Tests\IteratorAggregateStub(['a' => 1, 'b' => 2, 'c' => 5, 'd' => 8]),
'xml' => new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><doc><elem>foo</elem><elem>bar</elem><elem>baz</elem></doc>'),
]
--EXPECT--


5

5

5

8

5

5

5

foo

0 comments on commit 1daf5b5

Please sign in to comment.