This commit is contained in:
Dan Harrin
2025-05-21 08:49:43 +01:00
parent 895da959e0
commit 1d295c884d
2 changed files with 16 additions and 23 deletions
@@ -22,7 +22,7 @@ abstract class ViewComponent extends Component implements Htmlable
protected string | Closure | null $defaultView = null;
/**
* @var array<array-key, array<string|int, mixed>|Closure>
* @var array<array<string, mixed> | Closure>
*/
protected array $viewData = [];
@@ -66,7 +66,7 @@ abstract class ViewComponent extends Component implements Htmlable
}
/**
* @param array<string, mixed>|Closure $data
* @param array<string, mixed> | Closure $data
*/
public function viewData(array | Closure $data): static
{
@@ -104,9 +104,10 @@ abstract class ViewComponent extends Component implements Htmlable
*/
public function getViewData(): array
{
return Arr::mapWithKeys($this->viewData, function (mixed $value) {
return $this->evaluate($value);
});
return Arr::mapWithKeys(
$this->viewData,
fn (mixed $data): array => $this->evaluate($data) ?? [],
);
}
public function toHtml(): string
+10 -18
View File
@@ -6,38 +6,30 @@ use Filament\Tests\TestCase;
uses(TestCase::class);
it('can have view data', function () {
$view = View::make('test')
$component = View::make('test')
->viewData([
'key_a' => 'Value A',
'key_b' => 'Value B',
])
->viewData([]);
expect($view)
expect($component)
->getViewData()->toBe([
'key_a' => 'Value A',
'key_b' => 'Value B',
]);
});
it('can have view data with closure on numeric keys', function () {
$view = View::make('test')
->viewData([
'key_a' => 'Value A',
])
->viewData(function () {
// Closure result will be merged with the top-level array...
return ['string_keyed_closure' => 'string_keyed_closure'];
})
->viewData(function () {
// Closure result will be merged with the top-level array...
return ['string_keyed_closure_b' => 'string_keyed_closure_b'];
});
it('can have view data inside closures', function () {
$component = View::make('test')
->viewData(['key_a' => 'Value A'])
->viewData(fn (): array => ['closure_key_a' => 'Closure Value A'])
->viewData(fn (): array => ['closure_key_b' => 'Closure Value B']);
expect($view)
expect($component)
->getViewData()->toBe([
'key_a' => 'Value A',
'string_keyed_closure' => 'string_keyed_closure',
'string_keyed_closure_b' => 'string_keyed_closure_b',
'closure_key_a' => 'Closure Value A',
'closure_key_b' => 'Closure Value B',
]);
});