Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions packages/panels/src/Panel/Concerns/HasRenderHooks.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@

use Closure;
use Filament\Support\Facades\FilamentView;
use Filament\View\RenderHook;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Arr;
use ReflectionClass;

trait HasRenderHooks
{
Expand All @@ -12,6 +16,11 @@ trait HasRenderHooks
*/
protected array $renderHooks = [];

/**
* @var array<string, string>
*/
protected array $renderHookDirectories = [];

/**
* @param string | array<string> | null $scopes
*/
Expand All @@ -28,8 +37,57 @@ public function renderHook(string $name, Closure $hook, string | array | null $s
return $this;
}

public function discoverRenderHooks(string $in, string $for): static
{
$this->renderHookDirectories[$in] = $for;

return $this;
}

protected function registerRenderHooks(): void
{
$filesystem = app(Filesystem::class);

foreach ($this->renderHookDirectories as $in => $for) {
if (blank($in) || blank($for)) {
continue;
}

if (! $filesystem->exists($in)) {
continue;
}

$namespace = str($for);

foreach ($filesystem->allFiles($in) as $file) {
$class = (string) $namespace
->append('\\', $file->getRelativePathname())
->replace([DIRECTORY_SEPARATOR, '.php'], ['\\', '']);

if (! class_exists($class)) {
continue;
}

if ((new ReflectionClass($class))->isAbstract()) {
continue;
}

if (! is_subclass_of($class, RenderHook::class)) {
continue;
}

$hooks = $class::getRenderHooks();

foreach (Arr::wrap($hooks) as $hook) {
$this->renderHook(
$hook,
fn (array $data, array $scopes) => app()->call([app($class), 'render'], ['data' => $data, 'scopes' => $scopes]),
$class::getScopes(),
);
}
}
}

foreach ($this->renderHooks as $hookName => $scopedHooks) {
foreach ($scopedHooks as $scope => $hooks) {
foreach ($hooks as $hook) {
Expand Down
27 changes: 27 additions & 0 deletions packages/panels/src/View/RenderHook.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace Filament\View;

use Illuminate\Contracts\View\View;

abstract class RenderHook
{
/**
* @return non-empty-array<string>|null
*/
public static function getScopes(): ?array
{
return null;
}

/**
* @return string | array<string>
*/
abstract public static function getRenderHooks(): string | array;

/**
* @param array<string> $scopes
* @param array<mixed> $data
*/
abstract public function render(array $scopes, array $data): View | string;
}
Loading