From bcc862c35c6703162da8a3da30331ec2a73ad504 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriel=20A=2E=20L=C3=B3pez=20L=C3=B3pez?= Date: Sun, 8 Sep 2024 12:01:19 -0400 Subject: [PATCH] #211: allow a Closure for each attribute on `ListView::itemViewAttributes()`. --- src/ListView.php | 8 +++++- tests/ListView/BaseTest.php | 50 +++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/src/ListView.php b/src/ListView.php index 4f15460bd..fcd3157c8 100644 --- a/src/ListView.php +++ b/src/ListView.php @@ -193,9 +193,15 @@ protected function renderItem(array|object $data, mixed $key, int $index): strin } $itemViewAttributes = is_callable($this->itemViewAttributes) - ? (array) call_user_func($this->itemViewAttributes, $data, $key, $index, $this) + ? (array)call_user_func($this->itemViewAttributes, $data, $key, $index, $this) : $this->itemViewAttributes; + foreach ($itemViewAttributes as $i => $attribute) { + if (is_callable($attribute)) { + $itemViewAttributes[$i] = $attribute($data, $key, $index, $this); + } + } + return Div::tag() ->attributes($itemViewAttributes) ->content("\n" . $content) diff --git a/tests/ListView/BaseTest.php b/tests/ListView/BaseTest.php index 6173d7693..4e26dfe87 100644 --- a/tests/ListView/BaseTest.php +++ b/tests/ListView/BaseTest.php @@ -278,4 +278,54 @@ public function testClosureForItemViewAttributes(): void ->render(), ); } + + public function testItemViewAttributesWithClosure(): void + { + Assert::equalsWithoutLE( + << +
+
Id: 1
Name: John
Age: 20
+
+
+
Id: 2
Name: Mary
Age: 21
+
+
Page 1 of 1
+ + HTML, + ListView::widget() + ->itemView(dirname(__DIR__) . '/Support/view/_listview.php') + ->itemViewAttributes([ + 'class' => static fn(array $data, $key, $index) => "id-{$data['id']}-key-{$key}-index-{$index}", + ]) + ->dataReader($this->createOffsetPaginator($this->data, 10)) + ->separator(PHP_EOL) + ->render(), + ); + } + + public function testClosureForItemViewAttributesWithClosure(): void + { + Assert::equalsWithoutLE( + << +
+
Id: 1
Name: John
Age: 20
+
+
+
Id: 2
Name: Mary
Age: 21
+
+
Page 1 of 1
+ + HTML, + ListView::widget() + ->itemView(dirname(__DIR__) . '/Support/view/_listview.php') + ->itemViewAttributes(static fn (array $data, $key, $index) => [ + 'class' => static fn(array $data, $key, $index) => "id-{$data['id']}-key-{$key}-index-{$index}", + ]) + ->dataReader($this->createOffsetPaginator($this->data, 10)) + ->separator(PHP_EOL) + ->render(), + ); + } }