Skip to content

Commit

Permalink
Add a hook to allow mass-preload of related data when rendering a pag…
Browse files Browse the repository at this point in the history
…e's blocks
  • Loading branch information
Voltra authored Jun 27, 2024
1 parent 0b1a47a commit e87b102
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 5 deletions.
23 changes: 18 additions & 5 deletions resources/views/components/page-blocks.blade.php
Original file line number Diff line number Diff line change
@@ -1,14 +1,27 @@
@aware(['page'])
@props(['blocks' => []])

@php
$groups = \Z3d0X\FilamentFabricator\Helpers::arrayRefsGroupBy($blocks, 'type');
foreach ($groups as $blockType => &$group) {
/**
* @var class-string<\Z3d0X\FilamentFabricator\PageBlocks\PageBlock> $blockClass
*/
$blockClass = FilamentFabricator::getPageBlockFromName($blockType);
if (!empty($blockClass)) {
$blockClass::preloadRelatedData($page, $group);
}
}
@endphp

@foreach ($blocks as $blockData)
@php
$pageBlock = \Z3d0X\FilamentFabricator\Facades\FilamentFabricator::getPageBlockFromName($blockData['type'])
$pageBlock = \Z3d0X\FilamentFabricator\Facades\FilamentFabricator::getPageBlockFromName($blockData['type']);
@endphp

@isset($pageBlock)
<x-dynamic-component
:component="$pageBlock::getComponent()"
:attributes="new \Illuminate\View\ComponentAttributeBag($pageBlock::mutateData($blockData['data']))"
/>
<x-dynamic-component :component="$pageBlock::getComponent()" :attributes="new \Illuminate\View\ComponentAttributeBag($pageBlock::mutateData($blockData['data']))" />
@endisset
@endforeach
23 changes: 23 additions & 0 deletions src/Helpers.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace Z3d0X\FilamentFabricator;

abstract class Helpers
{
/**
* Group an array of associative arrays by a given key
*
* @param array[] $arr
* @return array[]
*/
public static function arrayRefsGroupBy(array &$arr, string $key): array
{
$ret = [];

foreach ($arr as &$item) {
$ret[$item[$key]][] = &$item;
}

return $ret;
}
}
12 changes: 12 additions & 0 deletions src/PageBlocks/PageBlock.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Z3d0X\FilamentFabricator\PageBlocks;

use Filament\Forms\Components\Builder\Block;
use Z3d0X\FilamentFabricator\Models\Contracts\Page;

abstract class PageBlock
{
Expand All @@ -28,4 +29,15 @@ public static function mutateData(array $data): array
{
return $data;
}

/**
* Hook used to mass-preload related data to reduce the number of DB queries.
* For instance, to load model objects/data from their IDs
*
* @param (array{
* type: string,
* data: array,
* })[] $blocks - The array of blocks' data for the given page and the given block type
*/
public static function preloadRelatedData(Page $page, array &$blocks): void {}
}

0 comments on commit e87b102

Please sign in to comment.