diff --git a/src/Modifiers/CoreModifiers.php b/src/Modifiers/CoreModifiers.php index 36f9ff6bf0..5f6f6dc186 100644 --- a/src/Modifiers/CoreModifiers.php +++ b/src/Modifiers/CoreModifiers.php @@ -663,13 +663,13 @@ public function first($value, $params) } /** - * Flattens a multi-dimensional collection into a single dimension. + * Flattens a multi-dimensional collection into a single or arbitrary dimension. * * @return array */ - public function flatten($value) + public function flatten($value, $params) { - return collect($value)->flatten()->toArray(); + return collect($value)->flatten(Arr::get($params, 0, INF))->toArray(); } /** diff --git a/tests/Modifiers/FlattenTest.php b/tests/Modifiers/FlattenTest.php index 16137f896b..b50b3a1bb3 100644 --- a/tests/Modifiers/FlattenTest.php +++ b/tests/Modifiers/FlattenTest.php @@ -5,40 +5,80 @@ use Statamic\Modifiers\Modify; use Tests\TestCase; -/** - * @todo Add test with numeric indices - */ class FlattenTest extends TestCase { - /** @test */ - public function it_flattens_a_multidimensional_array(): void + /** + * @test + * + * @dataProvider flattenProvider + */ + public function it_flattens_an_array($depth, $expected): void { $input = [ - 'ingredients' => [ - 'spices' => ['garlic', 'cumin', 'ginger', 'turmeric', 'paprika', 'curry powder'], - 'vegetables' => ['tomatoes', 'onion'], - 'meat' => ['chicken'], + [ + 'foo', + [ + 'bar', + [ + 'baz', + ], + ], ], + 'zap', ]; - $expected = [ - 'garlic', - 'cumin', - 'ginger', - 'turmeric', - 'paprika', - 'curry powder', - 'tomatoes', - 'onion', - 'chicken', + $modified = $this->modify($input, $depth); + $this->assertEquals($expected, $modified); + } + + public static function flattenProvider() + { + return [ + 'depth null' => [null, ['foo', 'bar', 'baz', 'zap']], + 'depth 1' => [1, ['foo', ['bar', ['baz']], 'zap']], + 'depth 2' => [2, ['foo', 'bar', ['baz'], 'zap']], + 'depth 3' => [3, ['foo', 'bar', 'baz', 'zap']], + 'depth 4' => [4, ['foo', 'bar', 'baz', 'zap']], + ]; + } + + /** + * @test + * + * @dataProvider flattenWithKeysProvider + */ + public function it_flattens_an_array_with_keys($depth, $expected): void + { + $input = [ + [ + 'foo', + 'alfa' => [ + 'bar', + 'bravo' => [ + 'baz', + ], + ], + ], + 'zap', ]; - $modified = $this->modify($input); + $modified = $this->modify($input, $depth); $this->assertEquals($expected, $modified); } - private function modify(array $value) + public static function flattenWithKeysProvider() + { + return [ + 'depth null' => [null, ['foo', 'bar', 'baz', 'zap']], + 'depth 1' => [1, ['foo', ['bar', 'bravo' => ['baz']], 'zap']], + 'depth 2' => [2, ['foo', 'bar', ['baz'], 'zap']], + 'depth 3' => [3, ['foo', 'bar', 'baz', 'zap']], + 'depth 4' => [4, ['foo', 'bar', 'baz', 'zap']], + ]; + } + + private function modify(array $value, $param = null) { - return Modify::value($value)->flatten()->fetch(); + return Modify::value($value)->flatten($param)->fetch(); } }