Phase 0: Fundament für Inhaus
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m14s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 1m12s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 1m7s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 1m19s
CI / PHP 8.3 / mysql:8.0 (pull_request) Successful in 1m32s
CI / PHP 8.4 / mysql:8.0 (pull_request) Successful in 1m22s
CI / PHP 8.4 / mysql:8.4 (pull_request) Successful in 1m32s
CI / PHP 8.3 / mysql:8.4 (pull_request) Successful in 1m35s
CI / Build-Artefakte aktuell (pull_request) Failing after 1m7s

- Laravel 13 mit Filament 5 (Admin), Inertia 3 + Vue 3 + Vuetify 4 (Material 3)
- Anmeldung über Fortify (Login, Passwort vergessen/ändern), keine Selbstregistrierung
- Profil mit Profilbild (WebP in festen Größen), Personenseiten, Header mit Avatar-Menü
- Material-3-Farbschema aus der Primärfarbe, hell/dunkel/System pro Person
- Basis-Branding (Portalname, Logo, Primärfarbe) im Admin unter „Erscheinungsbild“
- Benutzerverwaltung im Admin, Zugang vorläufig über is_admin
- vendor/ (ohne Dev-Pakete) und Frontend-Build mitversioniert, Dev-Pakete in vendor-dev/
- PHPUnit-Tests gegen MySQL/MariaDB, Forgejo-CI-Matrix, Docker-Entwicklungsumgebung
- VERSION, CHANGELOG.md und CONTRIBUTING.md mit Release-Ablauf

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-25 20:35:30 +00:00
parent 7197eaebf2
commit 9c0f8de791
15771 changed files with 1564103 additions and 5 deletions

View file

@ -0,0 +1,39 @@
<?php
namespace Filament\Actions\Concerns;
use Filament\Actions\ActionGroup;
trait BelongsToGroup
{
protected ?ActionGroup $group = null;
public function group(?ActionGroup $group): static
{
$this->group = $group;
return $this;
}
public function getGroup(): ?ActionGroup
{
return $this->group;
}
public function getRootGroup(): ?ActionGroup
{
$group = $this->getGroup();
while ($group) {
$parentGroup = $group->getGroup();
if (! $parentGroup) {
break;
}
$group = $parentGroup;
}
return $group;
}
}

View file

@ -0,0 +1,50 @@
<?php
namespace Filament\Actions\Concerns;
use Filament\Actions\Contracts\HasActions;
use Livewire\Component;
trait BelongsToLivewire
{
protected Component $livewire;
public function livewire(Component $livewire): static
{
$this->livewire = $livewire;
return $this;
}
public function getLivewire(): ?object
{
if (isset($this->livewire)) {
return $this->livewire;
}
if ($livewire = $this->getSchemaContainer()?->getLivewire()) {
return $livewire;
}
if ($livewire = $this->getSchemaComponent()?->getLivewire()) {
return $livewire;
}
if ($livewire = $this->getTable()?->getLivewire()) {
return $livewire;
}
return $this->getGroup()?->getLivewire();
}
public function getHasActionsLivewire(): ?HasActions
{
$livewire = $this->getLivewire();
if (! $livewire instanceof HasActions) {
return null;
}
return $livewire;
}
}

View file

@ -0,0 +1,37 @@
<?php
namespace Filament\Actions\Concerns;
use Filament\Schemas\Components\Component;
use Filament\Schemas\Schema;
trait BelongsToSchemaComponent
{
protected ?Component $schemaComponent = null;
protected ?Schema $schemaContainer = null;
public function schemaComponent(?Component $component): static
{
$this->schemaComponent = $component;
return $this;
}
public function schemaContainer(?Schema $schema): static
{
$this->schemaContainer = $schema;
return $this;
}
public function getSchemaComponent(): ?Component
{
return $this->schemaComponent ?? $this->getSchemaContainer()?->getParentComponent() ?? $this->getGroup()?->getSchemaComponent();
}
public function getSchemaContainer(): ?Schema
{
return $this->schemaContainer ?? $this->getGroup()?->getSchemaContainer();
}
}

View file

@ -0,0 +1,27 @@
<?php
namespace Filament\Actions\Concerns;
use Filament\Tables\Table;
trait BelongsToTable
{
protected ?Table $table = null;
public function table(?Table $table): static
{
$this->table = $table;
return $this;
}
public function getTable(): ?Table
{
return $this->table ?? $this->getGroup()?->getTable();
}
public function hasTable(): bool
{
return $this->getTable() !== null;
}
}

View file

@ -0,0 +1,295 @@
<?php
namespace Filament\Actions\Concerns;
use BackedEnum;
use Closure;
use Illuminate\Auth\Access\Response;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Gate;
use LogicException;
use UnitEnum;
trait CanBeAuthorized
{
// Security: Actions do not have automatic policy-based authorization.
// Authorization defaults to `null` (allowed for all users).
// You must explicitly use `authorize()`, `visible()`, or
// `hidden()` to restrict access to custom actions.
protected mixed $authorization = null;
protected string | Closure | null $authorizationMessage = null;
protected bool | Closure $hasAuthorizationTooltip = false;
protected bool | Closure $hasAuthorizationNotification = false;
protected bool | string | UnitEnum | Closure | null $authorizeIndividualRecords = null;
/**
* @param Model | class-string | array<mixed> | null $arguments
*/
public function authorize(mixed $abilities, Model | string | array | null $arguments = null): static
{
$abilities = match (true) {
$abilities instanceof BackedEnum => $abilities->value,
$abilities instanceof UnitEnum => $abilities->name,
default => $abilities,
};
if (is_string($abilities) || is_array($abilities)) {
$this->authorization = [
'type' => 'all',
'abilities' => Arr::wrap($abilities),
'arguments' => Arr::wrap($arguments),
];
} else {
$this->authorization = $abilities;
}
return $this;
}
/**
* @param string | UnitEnum | array<string | UnitEnum> $abilities
* @param Model | array<mixed> | null $arguments
*/
public function authorizeAny(string | UnitEnum | array $abilities, Model | array | null $arguments = null): static
{
$abilities = match (true) {
$abilities instanceof BackedEnum => $abilities->value,
$abilities instanceof UnitEnum => $abilities->name,
default => $abilities,
};
$this->authorization = [
'type' => 'any',
'abilities' => Arr::wrap($abilities),
'arguments' => Arr::wrap($arguments),
];
return $this;
}
/**
* @param array<mixed> $arguments
* @return array<mixed>
*/
protected function parseAuthorizationArguments(array $arguments): array
{
if ($record = $this->getRecord()) {
array_unshift($arguments, $record);
} elseif ($model = $this->getModel()) {
array_unshift($arguments, $model);
}
return $arguments;
}
public function isAuthorized(): bool
{
if (! $this->hasTable()) {
return $this->resolveIsAuthorized();
}
if (! $this->prepareVisibilityCache()) {
return $this->resolveIsAuthorized();
}
return $this->cachedIsAuthorized ??= $this->resolveIsAuthorized();
}
protected function resolveIsAuthorized(): bool
{
if ($this->authorization === null) {
return $this->getHasActionsLivewire()?->getDefaultActionAuthorizationResponse($this)?->allowed() ?? true;
}
if (! is_array($this->authorization)) {
$response = $this->evaluate($this->authorization);
return match (true) {
$response instanceof Response => $response->allowed(),
default => (bool) $response,
};
}
$abilities = $this->authorization['abilities'] ?? [];
$arguments = $this->parseAuthorizationArguments($this->authorization['arguments'] ?? []);
$type = $this->authorization['type'] ?? null;
return match ($type) {
'all' => Gate::check($abilities, $arguments),
'any' => Gate::any($abilities, $arguments),
default => false,
};
}
public function getAuthorizationResponse(): Response
{
if ($this->authorization === null) {
return $this->getHasActionsLivewire()->getDefaultActionAuthorizationResponse($this) ?? Response::allow();
}
if (! is_array($this->authorization)) {
$response = $this->evaluate($this->authorization);
return match (true) {
$response instanceof Response => $response,
(bool) $response => Response::allow(),
default => Response::deny(),
};
}
$abilities = $this->authorization['abilities'] ?? [];
$arguments = $this->parseAuthorizationArguments($this->authorization['arguments'] ?? []);
$type = $this->authorization['type'] ?? null;
foreach ($abilities as $ability) {
$response = Gate::inspect($ability, Arr::wrap($arguments));
if (($type === 'any') && $response->allowed()) {
return $response;
}
if (($type === 'all') && $response->denied()) {
return $response;
}
}
return Response::allow();
}
public function getAuthorizationResponseWithMessage(): Response
{
$response = $this->getAuthorizationResponse();
if ($response->allowed()) {
return $response;
}
$message = $this->getAuthorizationMessage();
if (filled($message)) {
invade($response)->message = $message; /** @phpstan-ignore-line */
return $response;
}
if (blank($response->message())) {
throw new LogicException('An authorization was denied without a message.');
}
return $response;
}
public function authorizationMessage(string | Closure | null $message): static
{
$this->authorizationMessage = $message;
return $this;
}
public function getAuthorizationMessage(): ?string
{
return $this->evaluate($this->authorizationMessage);
}
public function authorizationTooltip(bool | Closure $condition = true): static
{
$this->hasAuthorizationTooltip = $condition;
return $this;
}
public function authorizationNotification(bool | Closure $condition = true): static
{
$this->hasAuthorizationNotification = $condition;
return $this;
}
public function hasAuthorizationTooltip(): bool
{
return (bool) $this->evaluate($this->hasAuthorizationTooltip);
}
public function hasAuthorizationNotification(): bool
{
return (bool) $this->evaluate($this->hasAuthorizationNotification);
}
public function isAuthorizedOrNotHiddenWhenUnauthorized(): bool
{
if (! $this->hasTable()) {
return $this->resolveIsAuthorizedOrNotHiddenWhenUnauthorized();
}
if (! $this->prepareVisibilityCache()) {
return $this->resolveIsAuthorizedOrNotHiddenWhenUnauthorized();
}
return $this->cachedIsAuthorizedOrNotHiddenWhenUnauthorized ??= $this->resolveIsAuthorizedOrNotHiddenWhenUnauthorized();
}
protected function resolveIsAuthorizedOrNotHiddenWhenUnauthorized(): bool
{
if (! $this->hasAuthorizationTooltip() && ! $this->hasAuthorizationNotification()) {
return $this->isAuthorized();
}
$response = $this->getAuthorizationResponse();
if ($response->allowed()) {
return true;
}
return filled($response->message()) || filled($this->getAuthorizationMessage());
}
public function authorizeIndividualRecords(bool | string | UnitEnum | Closure | null $callback = true): static
{
$this->authorizeIndividualRecords = $callback;
return $this;
}
public function getIndividualRecordAuthorizationResponse(Model $record): Response
{
if (is_string($this->authorizeIndividualRecords) || ($this->authorizeIndividualRecords instanceof UnitEnum)) {
return Gate::inspect($this->authorizeIndividualRecords, Arr::wrap($record));
}
$resolver = ($this->authorizeIndividualRecords instanceof Closure)
? $this->authorizeIndividualRecords
: $this->getHasActionsLivewire()->getDefaultActionIndividualRecordAuthorizationResponseResolver($this);
if (! $resolver) {
throw new LogicException('No function was passed to [authorizeIndividualRecords()].');
}
$response = $resolver($record);
if ($response instanceof Response) {
return $response;
}
return $response ? Response::allow() : Response::deny();
}
public function shouldAuthorizeIndividualRecords(): bool
{
return filled($this->authorizeIndividualRecords) && ($this->authorizeIndividualRecords !== false);
}
public function hasAuthorization(): bool
{
return $this->authorization !== null
|| $this->authorizeIndividualRecords !== null
|| $this->hasAuthorizationNotification !== false
|| $this->hasAuthorizationTooltip !== false
|| $this->authorizationMessage !== null;
}
}

View file

@ -0,0 +1,30 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
trait CanBeBooted
{
protected ?Closure $bootUsing = null;
protected bool $isBooted = false;
public function bootUsing(?Closure $callback): static
{
$this->bootUsing = $callback;
return $this;
}
public function boot(): void
{
if ($this->isBooted) {
return;
}
$this->isBooted = true;
$this->evaluate($this->bootUsing);
}
}

View file

@ -0,0 +1,56 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
trait CanBeDisabled
{
protected bool | Closure $isDisabled = false;
public function disabled(bool | Closure $condition = true): static
{
$this->isDisabled = $condition;
return $this;
}
public function isDisabled(): bool
{
if ($this->evaluate($this->isDisabled)) {
return true;
}
if ($this->isHidden()) {
return true;
}
// Past `isHidden()` returning false, `isAuthorizedOrNotHiddenWhenUnauthorized()`
// must have returned true — which means at least one of `hasAuthorizationTooltip()`,
// `hasAuthorizationNotification()`, or `isAuthorized()` is true. The branches below
// exploit that disjunction to decide without re-calling `isAuthorized()`.
if ($this->hasAuthorizationNotification()) {
return false;
}
if (! $this->hasAuthorizationTooltip()) {
// `hasAuthorizationTooltip()` and `hasAuthorizationNotification()` are both
// false, so `isAuthorized()` must be true, and this is not disabled.
return false;
}
return ! $this->isAuthorized();
}
public function isEnabled(): bool
{
return ! $this->isDisabled();
}
public function hasDisabled(): bool
{
return $this->isDisabled !== false;
}
}

View file

@ -0,0 +1,149 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
use Filament\Actions\ActionGroup;
use Filament\Support\ArrayRecord;
use Illuminate\Database\Eloquent\Model;
trait CanBeHidden
{
protected bool | Closure $isHidden = false;
protected bool | Closure $isVisible = true;
protected ?bool $cachedIsAuthorized = null;
protected ?bool $cachedIsHidden = null;
protected ?bool $cachedIsHiddenInGroup = null;
protected ?bool $cachedIsAuthorizedOrNotHiddenWhenUnauthorized = null;
protected ?string $cachedVisibilityRecordKey = null;
protected bool $hasVisibilityCache = false;
public function hidden(bool | Closure $condition = true): static
{
$this->isHidden = $condition;
return $this;
}
public function visible(bool | Closure $condition = true): static
{
$this->isVisible = $condition;
return $this;
}
public function isHidden(): bool
{
if (! $this->hasTable()) {
return $this->getGroup()?->baseIsHidden()
? true
: $this->isHiddenInGroup();
}
if (! $this->prepareVisibilityCache()) {
return $this->getGroup()?->baseIsHidden()
? true
: $this->isHiddenInGroup();
}
return $this->cachedIsHidden ??= ($this->getGroup()?->baseIsHidden()
? true
: $this->isHiddenInGroup());
}
public function isHiddenInGroup(): bool
{
if (! $this->hasTable()) {
return $this->resolveIsHiddenInGroup();
}
if (! $this->prepareVisibilityCache()) {
return $this->resolveIsHiddenInGroup();
}
return $this->cachedIsHiddenInGroup ??= $this->resolveIsHiddenInGroup();
}
protected function resolveIsHiddenInGroup(): bool
{
if ($this->evaluate($this->isHidden)) {
return true;
}
if (! $this->evaluate($this->isVisible)) {
return true;
}
if ($this instanceof ActionGroup) {
foreach ($this->getActions() as $action) {
if (! $action->isHiddenInGroup()) {
return false;
}
}
return true;
}
return ! $this->isAuthorizedOrNotHiddenWhenUnauthorized();
}
public function isVisible(): bool
{
return ! $this->isHidden();
}
protected function prepareVisibilityCache(): bool
{
$current = $this->getCurrentVisibilityRecordKey();
if ($current === null) {
$this->clearVisibilityCache();
return false;
}
if ($this->hasVisibilityCache && ($this->cachedVisibilityRecordKey === $current)) {
return true;
}
$this->clearVisibilityCache();
$this->cachedVisibilityRecordKey = $current;
$this->hasVisibilityCache = true;
return true;
}
protected function getCurrentVisibilityRecordKey(): ?string
{
$record = $this->getRecord();
if ($record instanceof Model) {
return (string) spl_object_id($record);
}
if (is_array($record)) {
$key = $record[ArrayRecord::getKeyName()] ?? null;
return ($key === null) ? null : (string) $key;
}
return '__null__';
}
public function clearVisibilityCache(): void
{
$this->cachedIsAuthorized = null;
$this->cachedIsHidden = null;
$this->cachedIsHiddenInGroup = null;
$this->cachedIsAuthorizedOrNotHiddenWhenUnauthorized = null;
$this->cachedVisibilityRecordKey = null;
$this->hasVisibilityCache = false;
}
}

View file

@ -0,0 +1,27 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
trait CanBeLabeledFrom
{
protected string | Closure | null $labeledFrom = null;
public function labeledFrom(string | Closure | null $breakpoint = null): static
{
$this->labeledFrom = $breakpoint;
return $this;
}
public function getLabeledFromBreakpoint(): ?string
{
return $this->evaluate($this->labeledFrom);
}
public function hasLabeledFromBreakpoint(): bool
{
return $this->labeledFrom !== null;
}
}

View file

@ -0,0 +1,54 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
use Filament\Actions\Action;
use Filament\Schemas\Schema;
trait CanBeMounted
{
protected ?Closure $mountUsing = null;
/**
* @param array<string, mixed> $parameters
*/
public function mount(array $parameters): mixed
{
try {
return $this->evaluate($this->getMountUsing(), $parameters);
} finally {
$this->clearVisibilityCache();
}
}
public function mountUsing(?Closure $callback): static
{
$this->mountUsing = $callback;
return $this;
}
/**
* @param array<string, mixed> | Closure | null $data
*/
public function fillForm(array | Closure | null $data): static
{
$this->mountUsing(static function (Action $action, ?Schema $schema) use ($data): void {
$schema?->fill($action->evaluate($data));
});
return $this;
}
public function getMountUsing(): Closure
{
return $this->mountUsing ?? static function (?Schema $schema = null): void {
if (! $schema) {
return;
}
$schema->fill();
};
}
}

View file

@ -0,0 +1,27 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
trait CanBeOutlined
{
protected bool | Closure $isOutlined = false;
public function outlined(bool | Closure $condition = true): static
{
$this->isOutlined = $condition;
return $this;
}
public function isOutlined(): bool
{
return (bool) $this->evaluate($this->isOutlined);
}
public function hasOutlined(): bool
{
return $this->isOutlined !== false;
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
trait CanBeRateLimited
{
protected int | Closure | null $rateLimit = null;
public function rateLimit(int | Closure | null $maxAttempts): static
{
$this->rateLimit = $maxAttempts;
return $this;
}
public function getRateLimit(): ?int
{
return $this->evaluate($this->rateLimit);
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
trait CanBeSorted
{
protected int | Closure | null $sort = null;
public function sort(int | Closure | null $sort): static
{
$this->sort = $sort;
return $this;
}
public function getSort(): int
{
return $this->evaluate($this->sort) ?? 0;
}
}

View file

@ -0,0 +1,20 @@
<?php
namespace Filament\Actions\Concerns;
trait CanCallParentAction
{
protected ?string $parentActionCallLivewireClickHandler = null;
public function callParent(?string $handler): static
{
$this->parentActionCallLivewireClickHandler = $handler;
return $this;
}
public function getParentActionCallLivewireClickHandler(): ?string
{
return $this->parentActionCallLivewireClickHandler;
}
}

View file

@ -0,0 +1,27 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
trait CanClose
{
protected bool | Closure $shouldClose = false;
public function close(bool | Closure $condition = true): static
{
$this->shouldClose = $condition;
return $this;
}
public function shouldClose(): bool
{
return (bool) $this->evaluate($this->shouldClose);
}
public function hasClose(): bool
{
return $this->shouldClose !== false;
}
}

View file

@ -0,0 +1,25 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
trait CanCustomizeProcess
{
protected ?Closure $using = null;
public function using(?Closure $using): static
{
$this->using = $using;
return $this;
}
/**
* @param array<string, mixed> $parameters
*/
public function process(?Closure $default, array $parameters = []): mixed
{
return $this->evaluate($this->using ?? $default, $parameters);
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
trait CanDeselectRecordsAfterCompletion
{
protected bool | Closure $shouldDeselectRecordsAfterCompletion = false;
public function deselectRecordsAfterCompletion(bool | Closure $condition = true): static
{
$this->shouldDeselectRecordsAfterCompletion = $condition;
return $this;
}
public function shouldDeselectRecordsAfterCompletion(): bool
{
return (bool) $this->evaluate($this->shouldDeselectRecordsAfterCompletion);
}
}

View file

@ -0,0 +1,137 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
trait CanDispatchEvent
{
protected string | Closure | null $event = null;
/**
* @var array<mixed> | Closure
*/
protected array | Closure $eventData = [];
protected string | bool $dispatchDirection = false;
protected ?string $dispatchToComponent = null;
/**
* @param array<mixed> | Closure $data
*/
public function dispatch(
string | Closure | null $event,
array | Closure $data = [],
): static {
$this->event = $event;
$this->eventData($data);
$this->dispatchDirection = false;
return $this;
}
/**
* @param array<int, mixed> | Closure $data
*/
public function dispatchSelf(
string | Closure | null $event,
array | Closure $data = [],
): static {
$this->dispatch($event, $data);
$this->dispatchDirection = 'self';
return $this;
}
/**
* @param array<int, mixed> | Closure $data
*/
public function dispatchTo(
string $component,
string | Closure | null $event,
array | Closure $data = [],
): static {
$this->dispatch($event, $data);
$this->dispatchDirection = 'to';
$this->dispatchToComponent = $component;
return $this;
}
/**
* @deprecated Use `dispatch()` instead.
*
* @param array<int, mixed> | Closure $data
*/
public function emit(
string | Closure | null $event,
array | Closure $data = [],
): static {
$this->dispatch($event, $data);
return $this;
}
/**
* @deprecated Use `dispatchSelf()` instead.
*
* @param array<int, mixed> | Closure $data
*/
public function emitSelf(
string | Closure | null $event,
array | Closure $data = [],
): static {
$this->dispatchSelf($event, $data);
return $this;
}
/**
* @deprecated Use `dispatchTo()` instead.
*
* @param array<int, mixed> | Closure $data
*/
public function emitTo(
string $component,
string | Closure | null $event,
array | Closure $data = [],
): static {
$this->dispatchTo($component, $event, $data);
return $this;
}
public function getEvent(): ?string
{
return $this->evaluate($this->event);
}
/**
* @param array<mixed> | Closure $data
*/
public function eventData(array | Closure $data): static
{
$this->eventData = $data;
return $this;
}
/**
* @return array<mixed>
*/
public function getEventData(): array
{
return $this->evaluate($this->eventData);
}
public function getDispatchDirection(): string | bool
{
return $this->dispatchDirection;
}
public function getDispatchToComponent(): ?string
{
return $this->dispatchToComponent;
}
}

View file

@ -0,0 +1,622 @@
<?php
namespace Filament\Actions\Concerns;
use AnourValar\EloquentSerialize\Facades\EloquentSerializeFacade;
use Closure;
use Filament\Actions\Action;
use Filament\Actions\ExportAction;
use Filament\Actions\ExportBulkAction;
use Filament\Actions\Exports\Enums\Contracts\ExportFormat as ExportFormatInterface;
use Filament\Actions\Exports\Enums\ExportFormat;
use Filament\Actions\Exports\ExportColumn;
use Filament\Actions\Exports\Exporter;
use Filament\Actions\Exports\Jobs\CreateXlsxFile;
use Filament\Actions\Exports\Jobs\ExportCompletion;
use Filament\Actions\Exports\Jobs\PrepareCsvExport;
use Filament\Actions\Exports\Models\Export;
use Filament\Actions\View\ActionsIconAlias;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Notifications\Notification;
use Filament\Schemas\Components\Actions;
use Filament\Schemas\Components\Fieldset;
use Filament\Schemas\Components\Flex;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Support\Enums\Size;
use Filament\Support\Enums\Width;
use Filament\Support\Facades\FilamentIcon;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Contracts\HasTable;
use Illuminate\Bus\PendingBatch;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Bus\PendingChain;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Number;
use Livewire\Component;
use LogicException;
trait CanExportRecords
{
/**
* @var class-string<Exporter>
*/
protected string $exporter;
protected ?string $job = null;
protected int | Closure $chunkSize = 100;
protected int | Closure $columnMappingColumns = 1;
protected int | Closure | null $maxRows = null;
protected string | Closure | null $csvDelimiter = null;
/**
* @var array<string, mixed> | Closure
*/
protected array | Closure $options = [];
protected string | Closure | null $fileDisk = null;
protected string | Closure | null $fileName = null;
/**
* @var array<ExportFormatInterface> | Closure | null
*/
protected array | Closure | null $formats = null;
protected ?Closure $modifyQueryUsing = null;
protected bool | Closure $hasColumnMapping = true;
protected bool | Closure $isEnablingVisibleTableColumnsByDefault = false;
protected string | Closure | null $authGuard = null;
protected function setUp(): void
{
parent::setUp();
$this->label(fn (ExportAction | ExportBulkAction $action): string => __('filament-actions::export.label', ['label' => $action->getPluralModelLabel()]));
$this->modalHeading(fn (ExportAction | ExportBulkAction $action): string => __('filament-actions::export.modal.heading', ['label' => $action->getTitleCasePluralModelLabel()]));
$this->modalSubmitActionLabel(__('filament-actions::export.modal.actions.export.label'));
$this->groupedIcon(FilamentIcon::resolve(ActionsIconAlias::EXPORT_ACTION_GROUPED) ?? Heroicon::ArrowDownTray);
$this->schema(fn (ExportAction | ExportBulkAction $action): array => [
...($action->hasColumnMapping() ? [Fieldset::make(__('filament-actions::export.modal.form.columns.label'))
->columns(match ($columns = $action->getColumnMappingColumns()) {
1 => 1,
2 => [
'sm' => 2,
'lg' => 2,
],
3 => [
'sm' => 2,
'lg' => 3,
],
default => [
'sm' => 2,
'md' => 3,
'lg' => $columns,
],
})
->schema(function () use ($action): array {
$isEnablingVisibleTableColumnsByDefault = $action->isEnablingVisibleTableColumnsByDefault();
$visibleTableColumnNames = $isEnablingVisibleTableColumnsByDefault ? $action->getVisibleTableColumnNames() : [];
$columns = $action->getExporter()::getVisibleColumns();
$hasMultipleToggleableColumns = count($columns) > 1;
return [
...($hasMultipleToggleableColumns ? [Actions::make([
Action::make('selectAll')
->label(__('filament-actions::export.modal.form.columns.actions.select_all.label'))
->link()
->size(Size::Small)
->action(function (Set $set) use ($columns): void {
foreach ($columns as $column) {
$set("{$column->getName()}.isEnabled", true);
}
})
->visible(function (Get $get) use ($columns): bool {
foreach ($columns as $column) {
if (! $get("{$column->getName()}.isEnabled")) {
return true;
}
}
return false;
}),
Action::make('deselectAll')
->label(__('filament-actions::export.modal.form.columns.actions.deselect_all.label'))
->link()
->size(Size::Small)
->action(function (Set $set) use ($columns): void {
foreach ($columns as $column) {
$set("{$column->getName()}.isEnabled", false);
}
})
->visible(function (Get $get) use ($columns): bool {
foreach ($columns as $column) {
if ($get("{$column->getName()}.isEnabled")) {
return true;
}
}
return false;
}),
])->columnSpanFull()] : []),
...array_map(
fn (ExportColumn $column): Flex => Flex::make([
Forms\Components\Checkbox::make('isEnabled')
->label(__('filament-actions::export.modal.form.columns.form.is_enabled.label', ['column' => $column->getName()]))
->hiddenLabel()
->default(
$isEnablingVisibleTableColumnsByDefault
? (in_array($column->getName(), $visibleTableColumnNames) && $column->isEnabledByDefault())
: $column->isEnabledByDefault()
)
->live()
->grow(false),
Forms\Components\TextInput::make('label')
->label(__('filament-actions::export.modal.form.columns.form.label.label', ['column' => $column->getName()]))
->hiddenLabel()
->default($column->getLabel())
->placeholder($column->getLabel())
->disabled(fn (Get $get): bool => ! $get('isEnabled'))
->required(fn (Get $get): bool => (bool) $get('isEnabled')),
])
->verticallyAlignCenter()
->statePath($column->getName()),
$columns,
),
];
})
->statePath('columnMap')] : []),
...$action->getExporter()::getOptionsFormComponents(),
]);
$this->action(function (ExportAction | ExportBulkAction $action, array $data, Component $livewire): void {
$exporter = $action->getExporter();
if ($livewire instanceof HasTable) {
$query = $livewire->getTableQueryForExport();
} else {
$query = $exporter::getModel()::query();
}
$query = $exporter::modifyQuery($query);
$options = array_merge(
$action->getOptions(),
Arr::except($data, ['columnMap']),
);
if ($this->modifyQueryUsing) {
$query = $this->evaluate($this->modifyQueryUsing, [
'query' => $query,
'options' => $options,
]) ?? $query;
}
$records = $action instanceof ExportBulkAction ? $action->getIndividuallyAuthorizedSelectedRecords() : null;
$totalRows = $records ? $records->count() : $query->toBase()->getCountForPagination();
if ((! $records) && $query->getQuery()->limit) {
$totalRows = min($totalRows, $query->getQuery()->limit);
}
$maxRows = $action->getMaxRows() ?? $totalRows;
if ($maxRows < $totalRows) {
$action->failureNotification(
Notification::make()
->title(__('filament-actions::export.notifications.max_rows.title'))
->body(trans_choice('filament-actions::export.notifications.max_rows.body', $maxRows, [
'count' => Number::format($maxRows),
]))
->danger(),
);
$action->failure();
return;
}
$authGuard = $action->getAuthGuard();
$user = auth($authGuard)->user();
if ($action->hasColumnMapping()) {
$columnMap = collect($exporter::getVisibleColumns())
->filter(fn (ExportColumn $column): bool => (bool) data_get($data['columnMap'], "{$column->getName()}.isEnabled", false))
->mapWithKeys(fn (ExportColumn $column): array => [
$column->getName() => data_get($data['columnMap'], "{$column->getName()}.label", $column->getLabel()),
])
->all();
} else {
$isEnablingVisibleTableColumnsByDefault = $action->isEnablingVisibleTableColumnsByDefault();
$visibleTableColumnNames = $isEnablingVisibleTableColumnsByDefault ? $action->getVisibleTableColumnNames() : [];
$columnMap = collect($exporter::getVisibleColumns())
->when(
$isEnablingVisibleTableColumnsByDefault,
fn ($columns): Collection => $columns->filter(
fn (ExportColumn $column): bool => in_array($column->getName(), $visibleTableColumnNames) && $column->isEnabledByDefault(),
),
)
->mapWithKeys(fn (ExportColumn $column): array => [$column->getName() => $column->getLabel()])
->all();
}
if (empty($columnMap)) {
Notification::make()
->title(__('filament-actions::export.notifications.no_columns.title'))
->body(__('filament-actions::export.notifications.no_columns.body'))
->danger()
->send();
$action->halt();
return;
}
$export = app(Export::class);
$export->user()->associate($user);
$export->exporter = $exporter;
$export->total_rows = $totalRows;
$exporter = $export->getExporter(
columnMap: $columnMap,
options: $options,
);
$export->file_disk = $action->getFileDisk() ?? $exporter->getFileDisk();
// Temporary save to obtain the sequence number of the export file.
$export->save();
// Delete the export directory to prevent data contamination
// from previous exports with the same ID.
$export->deleteFileDirectory();
$export->file_name = $action->getFileName($export) ?? $exporter->getFileName($export);
$export->save();
$formats = $action->getFormats() ?? $exporter->getFormats();
$hasCsv = in_array(ExportFormat::Csv, $formats);
$hasXlsx = in_array(ExportFormat::Xlsx, $formats);
$serializedQuery = EloquentSerializeFacade::serialize($query);
$job = $action->getJob();
$jobQueue = $exporter->getJobQueue();
$jobConnection = $exporter->getJobConnection();
$jobBatchName = $exporter->getJobBatchName();
// We do not want to send the loaded user relationship to the
// queue in job payloads, in case it contains attributes that
// are not serializable, such as binary columns.
$export->unsetRelation('user');
$makeCreateXlsxFileJob = fn (): CreateXlsxFile => app(CreateXlsxFile::class, [
'export' => $export,
'columnMap' => $columnMap,
'options' => $options,
]);
Bus::chain([
Bus::batch([app($job, [
'export' => $export,
'query' => $serializedQuery,
'columnMap' => $columnMap,
'options' => $options,
'chunkSize' => $action->getChunkSize(),
'records' => $records?->all(),
])])
->allowFailures()
->when(
filled($jobQueue),
fn (PendingBatch $batch) => $batch->onQueue($jobQueue),
)
->when(
filled($jobConnection),
fn (PendingBatch $batch) => $batch->onConnection($jobConnection),
)
->when(
filled($jobBatchName),
fn (PendingBatch $batch) => $batch->name($jobBatchName),
),
...(($hasXlsx && (! $hasCsv)) ? [$makeCreateXlsxFileJob()] : []),
app(ExportCompletion::class, [
'authGuard' => $authGuard,
'export' => $export,
'columnMap' => $columnMap,
'formats' => $formats,
'options' => $options,
]),
...(($hasXlsx && $hasCsv) ? [$makeCreateXlsxFileJob()] : []),
])
->when(
filled($jobQueue),
fn (PendingChain $chain) => $chain->onQueue($jobQueue),
)
->when(
filled($jobConnection),
fn (PendingChain $chain) => $chain->onConnection($jobConnection),
)
->dispatch();
if (
($jobConnection === 'sync')
|| (blank($jobConnection) && (config('queue.default') === 'sync'))
) {
$action->successNotification(null);
$action->successNotificationTitle(null);
return;
}
$action->successNotification(
Notification::make()
->title($action->getSuccessNotificationTitle())
->body(trans_choice('filament-actions::export.notifications.started.body', $export->total_rows, [
'count' => Number::format($export->total_rows),
]))
->success(),
);
});
$this->defaultColor('gray');
$this->modalWidth(static fn (ExportAction | ExportBulkAction $action): Width => match ($action->getColumnMappingColumns()) {
1 => Width::Medium,
2 => Width::ThreeExtraLarge,
3 => Width::FiveExtraLarge,
default => Width::SevenExtraLarge,
});
$this->successNotificationTitle(__('filament-actions::export.notifications.started.title'));
if (! $this instanceof ExportBulkAction) {
$this->model(fn (ExportAction $action): string => $action->getExporter()::getModel());
}
}
public static function getDefaultName(): ?string
{
return 'export';
}
public function columnMappingColumns(int | Closure $columns): static
{
$this->columnMappingColumns = $columns;
return $this;
}
public function getColumnMappingColumns(): int
{
return $this->evaluate($this->columnMappingColumns);
}
/**
* @param class-string<Exporter> $exporter
*/
public function exporter(string $exporter): static
{
$this->exporter = $exporter;
return $this;
}
/**
* @return array<string>
*/
public function getVisibleTableColumnNames(): array
{
if (! $this->getLivewire() instanceof HasTable) {
throw new LogicException('Cannot get visible table columns from a non-table Livewire component.');
}
return array_keys($this->getLivewire()->getTable()->getVisibleColumns());
}
/**
* @param class-string | null $job
*/
public function job(?string $job): static
{
$this->job = $job;
return $this;
}
public function chunkSize(int | Closure $size): static
{
$this->chunkSize = $size;
return $this;
}
public function maxRows(int | Closure | null $rows): static
{
$this->maxRows = $rows;
return $this;
}
public function csvDelimiter(string | Closure | null $delimiter): static
{
$this->csvDelimiter = $delimiter;
return $this;
}
/**
* @return class-string<Exporter>
*/
public function getExporter(): string
{
return $this->exporter;
}
/**
* @return class-string
*/
public function getJob(): string
{
return $this->job ?? PrepareCsvExport::class;
}
public function getChunkSize(): int
{
return $this->evaluate($this->chunkSize);
}
public function getMaxRows(): ?int
{
return $this->evaluate($this->maxRows);
}
/**
* @param array<string, mixed> | Closure $options
*/
public function options(array | Closure $options): static
{
$this->options = $options;
return $this;
}
/**
* @return array<string, mixed>
*/
public function getOptions(): array
{
return $this->evaluate($this->options);
}
public function fileDisk(string | Closure | null $disk): static
{
$this->fileDisk = $disk;
return $this;
}
public function getFileDisk(): ?string
{
return $this->evaluate($this->fileDisk);
}
public function fileName(string | Closure | null $name): static
{
$this->fileName = $name;
return $this;
}
public function getFileName(Export $export): ?string
{
return $this->evaluate($this->fileName, [
'export' => $export,
]);
}
/**
* @param array<ExportFormatInterface> | Closure | null $formats
*/
public function formats(array | Closure | null $formats): static
{
$this->formats = $formats;
return $this;
}
/**
* @return array<ExportFormatInterface> | null
*/
public function getFormats(): ?array
{
return $this->evaluate($this->formats);
}
public function modifyQueryUsing(?Closure $callback): static
{
// Security: Exports do not check per-record policies. Use this
// to scope the query to records the user is authorized to see.
$this->modifyQueryUsing = $callback;
return $this;
}
public function columnMapping(bool | Closure $condition = true): static
{
$this->hasColumnMapping = $condition;
return $this;
}
public function hasColumnMapping(): bool
{
return (bool) $this->evaluate($this->hasColumnMapping);
}
public function enableVisibleTableColumnsByDefault(bool | Closure $condition = true): static
{
$this->isEnablingVisibleTableColumnsByDefault = $condition;
return $this;
}
public function isEnablingVisibleTableColumnsByDefault(): bool
{
return (bool) $this->evaluate($this->isEnablingVisibleTableColumnsByDefault);
}
public function authGuard(string | Closure | null $authGuard): static
{
$this->authGuard = $authGuard;
return $this;
}
public function getAuthGuard(): string
{
$guard = $this->evaluate($this->authGuard);
if (filled($guard)) {
return $guard;
}
if (class_exists(Filament::class) && Filament::isServing()) {
return Filament::getAuthGuard();
}
$authGuard = auth();
if (! property_exists($authGuard, 'name')) {
return config('auth.defaults.guard') ?? 'web';
}
return $authGuard->name;
}
/**
* @param Model | array<string, mixed> | null $record
* @return Model | array<string, mixed> | null
*/
protected function ensureCorrectRecordType(Model | array | null $record): Model | array | null
{
return $record;
}
}

View file

@ -0,0 +1,36 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
trait CanFetchSelectedRecords
{
protected bool | Closure $shouldFetchSelectedRecords = true;
protected int | Closure | null $selectedRecordsChunkSize = null;
public function fetchSelectedRecords(bool | Closure $condition = true): static
{
$this->shouldFetchSelectedRecords = $condition;
return $this;
}
public function shouldFetchSelectedRecords(): bool
{
return (bool) $this->evaluate($this->shouldFetchSelectedRecords);
}
public function chunkSelectedRecords(int | Closure | null $chunkSize = 100): static
{
$this->selectedRecordsChunkSize = $chunkSize;
return $this;
}
public function getSelectedRecordsChunkSize(): ?int
{
return $this->evaluate($this->selectedRecordsChunkSize);
}
}

View file

@ -0,0 +1,319 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
use DanHarrin\LivewireRateLimiting\Exceptions\TooManyRequestsException;
use Filament\Notifications\Notification;
use Illuminate\Auth\Access\Response;
trait CanNotify
{
protected Notification | Closure | null $failureNotification = null;
protected bool $isFailureNotificationDisabled = false;
protected Notification | Closure | null $successNotification = null;
protected bool $isSuccessNotificationDisabled = false;
protected Notification | Closure | null $unauthorizedNotification = null;
protected bool $isUnauthorizedNotificationDisabled = false;
protected Notification | Closure | null $rateLimitedNotification = null;
protected bool $isRateLimitedNotificationDisabled = false;
protected string | Closure | null $failureNotificationTitle = null;
protected string | Closure | null $successNotificationTitle = null;
protected string | Closure | null $unauthorizedNotificationTitle = null;
protected string | Closure | null $rateLimitedNotificationTitle = null;
protected string | Closure | null $failureNotificationBody = null;
protected string | Closure | null $missingBulkAuthorizationFailureNotificationMessage = null;
protected string | Closure | null $missingBulkProcessingFailureNotificationMessage = null;
public function missingBulkAuthorizationFailureNotificationMessage(string | Closure | null $message): static
{
$this->missingBulkAuthorizationFailureNotificationMessage = $message;
return $this;
}
public function missingBulkProcessingFailureNotificationMessage(string | Closure | null $message): static
{
$this->missingBulkProcessingFailureNotificationMessage = $message;
return $this;
}
/**
* @return array<string, mixed>
*/
protected function getFailureNotificationNamedInjections(): array
{
$processingFailureMessages = $this->getBulkProcessingFailureMessages();
return [
'authorizationFailureMessages' => $this->bulkAuthorizationFailureMessages,
'failureCount' => $this->totalSelectedRecordsCount - $this->successfulSelectedRecordsCount,
'failureMessages' => [...$this->bulkAuthorizationFailureMessages, ...$processingFailureMessages],
'isAll' => ! $this->successfulSelectedRecordsCount,
'missingAuthorizationFailureMessageCount' => $this->bulkAuthorizationFailureWithoutMessageCount,
'missingProcessingFailureMessageCount' => $this->bulkProcessingFailureWithoutMessageCount,
'processingFailureMessages' => $processingFailureMessages,
'successCount' => $this->successfulSelectedRecordsCount,
'totalCount' => $this->totalSelectedRecordsCount,
];
}
public function sendFailureNotification(): static
{
if ($this->isFailureNotificationDisabled) {
return $this;
}
$notification = $this->evaluate($this->failureNotification, [
...$this->getFailureNotificationNamedInjections(),
'notification' => $notification = Notification::make()
->when(
$this->successfulSelectedRecordsCount,
fn (Notification $notification) => $notification->warning(),
fn (Notification $notification) => $notification->danger(),
)
->title($this->getFailureNotificationTitle())
->body($this->getFailureNotificationBody())
->persistent(),
]) ?? $notification;
if (filled($notification?->getTitle())) {
$notification->send();
}
return $this;
}
public function failureNotification(Notification | Closure | null $notification): static
{
$this->failureNotification = $notification;
$this->isFailureNotificationDisabled = $notification === null;
return $this;
}
/**
* @deprecated Use `failureNotificationTitle()` instead.
*/
public function failureNotificationMessage(string | Closure | null $message): static
{
return $this->failureNotificationTitle($message);
}
public function failureNotificationTitle(string | Closure | null $title): static
{
$this->failureNotificationTitle = $title;
return $this;
}
public function failureNotificationBody(string | Closure | null $body): static
{
$this->failureNotificationBody = $body;
return $this;
}
public function sendSuccessNotification(): static
{
if ($this->isSuccessNotificationDisabled) {
return $this;
}
$notification = $this->evaluate($this->successNotification, [
'notification' => $notification = Notification::make()
->success()
->title($this->getSuccessNotificationTitle()),
]) ?? $notification;
if (filled($notification?->getTitle())) {
$notification->send();
}
return $this;
}
public function successNotification(Notification | Closure | null $notification): static
{
$this->successNotification = $notification;
$this->isSuccessNotificationDisabled = $notification === null;
return $this;
}
/**
* @deprecated Use `successNotificationTitle()` instead.
*/
public function successNotificationMessage(string | Closure | null $message): static
{
return $this->successNotificationTitle($message);
}
public function successNotificationTitle(string | Closure | null $title): static
{
$this->successNotificationTitle = $title;
return $this;
}
public function sendUnauthorizedNotification(Response $response): static
{
if ($this->isUnauthorizedNotificationDisabled) {
return $this;
}
$notification = $this->evaluate($this->unauthorizedNotification, [
'notification' => $notification = Notification::make()
->danger()
->title($this->getUnauthorizedNotificationTitle($response) ?? $response->message())
->persistent(),
'response' => $response,
]) ?? $notification;
if (filled($notification?->getTitle())) {
$notification->send();
}
return $this;
}
public function unauthorizedNotification(Notification | Closure | null $notification): static
{
$this->unauthorizedNotification = $notification;
$this->isUnauthorizedNotificationDisabled = $notification === null;
return $this;
}
public function unauthorizedNotificationTitle(string | Closure | null $title): static
{
$this->unauthorizedNotificationTitle = $title;
return $this;
}
public function sendRateLimitedNotification(TooManyRequestsException $exception): static
{
if ($this->isRateLimitedNotificationDisabled) {
return $this;
}
$notification = $this->evaluate($this->rateLimitedNotification, [
'exception' => $exception,
'minutes' => $exception->minutesUntilAvailable,
'notification' => $notification = Notification::make()
->danger()
->title($this->getRateLimitedNotificationTitle($exception) ?? __('filament-actions::notifications.throttled.title', [
'seconds' => $exception->secondsUntilAvailable,
'minutes' => $exception->minutesUntilAvailable,
]))
->body(__('filament-actions::notifications.throttled.body', [
'seconds' => $exception->secondsUntilAvailable,
'minutes' => $exception->minutesUntilAvailable,
])),
'seconds' => $exception->secondsUntilAvailable,
]) ?? $notification;
$notification->send();
return $this;
}
public function rateLimitedNotification(Notification | Closure | null $notification): static
{
$this->rateLimitedNotification = $notification;
$this->isRateLimitedNotificationDisabled = $notification === null;
return $this;
}
public function rateLimitedNotificationTitle(string | Closure | null $title): static
{
$this->rateLimitedNotificationTitle = $title;
return $this;
}
public function getSuccessNotificationTitle(): ?string
{
return $this->evaluate($this->successNotificationTitle);
}
public function getFailureNotificationTitle(): ?string
{
return $this->evaluate($this->failureNotificationTitle, $this->getFailureNotificationNamedInjections());
}
public function getFailureNotificationBody(): ?string
{
$body = $this->evaluate($this->failureNotificationBody, $this->getFailureNotificationNamedInjections());
if (filled($body)) {
return $body;
}
$messages = [
...$this->bulkAuthorizationFailureMessages,
...($this->bulkAuthorizationFailureWithoutMessageCount && filled($message = $this->evaluate(
$this->missingBulkAuthorizationFailureNotificationMessage,
[
'count' => $this->bulkAuthorizationFailureWithoutMessageCount,
'failureCount' => $this->bulkAuthorizationFailureWithoutMessageCount,
'isAll' => $this->bulkAuthorizationFailureWithoutMessageCount === $this->totalSelectedRecordsCount,
'total' => $this->totalSelectedRecordsCount,
'totalCount' => $this->totalSelectedRecordsCount,
],
)) ? [$message] : []),
...$this->getBulkProcessingFailureMessages(),
...($this->bulkProcessingFailureWithoutMessageCount && filled($message = $this->evaluate(
$this->missingBulkProcessingFailureNotificationMessage,
[
'count' => $this->bulkProcessingFailureWithoutMessageCount,
'failureCount' => $this->bulkProcessingFailureWithoutMessageCount,
'isAll' => $this->bulkProcessingFailureWithoutMessageCount === $this->totalSelectedRecordsCount,
'total' => $this->totalSelectedRecordsCount,
'totalCount' => $this->totalSelectedRecordsCount,
],
)) ? [$message] : []),
];
return implode(
'',
array_map(
fn (string $message): string => "<p>{$message}</p>",
$messages,
),
);
}
public function getUnauthorizedNotificationTitle(Response $response): ?string
{
return $this->evaluate($this->unauthorizedNotificationTitle, [
'response' => $response,
]);
}
public function getRateLimitedNotificationTitle(TooManyRequestsException $exception): ?string
{
return $this->evaluate($this->rateLimitedNotificationTitle, [
'exception' => $exception,
'minutes' => $exception->minutesUntilAvailable,
'seconds' => $exception->secondsUntilAvailable,
]);
}
}

View file

@ -0,0 +1,813 @@
<?php
namespace Filament\Actions\Concerns;
use BackedEnum;
use Closure;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Actions\View\ActionsIconAlias;
use Filament\Support\Enums\Alignment;
use Filament\Support\Enums\SlideOverPosition;
use Filament\Support\Enums\Width;
use Filament\Support\Facades\FilamentIcon;
use Filament\Support\Icons\Heroicon;
use Filament\Support\View\Components\ModalComponent;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Arr;
trait CanOpenModal
{
/**
* @var array<string, Action | ActionGroup>
*/
protected array $cachedExtraModalFooterActions;
/**
* @var array<Action | ActionGroup> | Closure
*/
protected array | Closure $extraModalFooterActions = [];
protected bool | Closure | null $isModalFooterSticky = null;
protected bool | Closure | null $isModalHeaderSticky = null;
/**
* @var array<string, Action>
*/
protected array $cachedModalActions;
/**
* @var array<Action | Closure>
*/
protected array $modalActions = [];
protected bool | Closure $isModalSlideOver = false;
protected SlideOverPosition | Closure | null $modalSlideOverPosition = null;
protected Alignment | string | Closure | null $modalAlignment = null;
/**
* @var array<string, Action | ActionGroup>
*/
protected array $cachedModalFooterActions;
/**
* @var array<Action> | Closure | null
*/
protected array | Closure | null $modalFooterActions = null;
protected Alignment | string | Closure | null $modalFooterActionsAlignment = null;
protected Action | bool | Closure | null $modalCancelAction = null;
protected string | Closure | null $modalCancelActionLabel = null;
protected Action | bool | Closure | null $modalSubmitAction = null;
protected string | Closure | null $modalSubmitActionLabel = null;
protected View | Htmlable | Closure | null $modalContent = null;
protected View | Htmlable | Closure | null $modalContentFooter = null;
protected string | Htmlable | Closure | null $modalHeading = null;
protected string | Htmlable | Closure | null $modalDescription = null;
protected Width | string | Closure | null $modalWidth = null;
protected bool | Closure | null $hasModal = null;
protected bool | Closure | null $isModalHidden = null;
protected bool | Closure | null $isModalClickThrough = null;
protected bool | Closure | null $hasModalCloseButton = null;
protected bool | Closure | null $isModalClosedByClickingAway = null;
protected bool | Closure | null $isModalClosedByEscaping = null;
protected bool | Closure | null $isModalAutofocused = null;
protected bool | Closure | null $hasUnsavedChangesAlert = null;
protected string | BackedEnum | Htmlable | Closure | null $modalIcon = null;
/**
* @var string | array<string> | Closure | null
*/
protected string | array | Closure | null $modalIconColor = null;
public function modalClickThrough(bool | Closure | null $condition = true): static
{
$this->isModalClickThrough = $condition;
return $this;
}
public function closeModalByClickingAway(bool | Closure | null $condition = true): static
{
$this->isModalClosedByClickingAway = $condition;
return $this;
}
public function closeModalByEscaping(bool | Closure | null $condition = true): static
{
$this->isModalClosedByEscaping = $condition;
return $this;
}
public function unsavedChangesAlert(bool | Closure | null $condition = true): static
{
$this->hasUnsavedChangesAlert = $condition;
return $this;
}
/**
* @deprecated Use `modalAlignment(Alignment::Center)` instead.
*/
public function centerModal(bool | Closure | null $condition = true): static
{
if ($this->evaluate($condition)) {
$this->modalAlignment(Alignment::Center);
}
return $this;
}
public function modalAlignment(Alignment | string | Closure | null $alignment = null): static
{
$this->modalAlignment = $alignment;
return $this;
}
public function modalCloseButton(bool | Closure | null $condition = true): static
{
$this->hasModalCloseButton = $condition;
return $this;
}
public function modalAutofocus(bool | Closure | null $condition = true): static
{
$this->isModalAutofocused = $condition;
return $this;
}
public function modalIcon(string | BackedEnum | Htmlable | Closure | null $icon = null): static
{
$this->modalIcon = $icon;
return $this;
}
/**
* @param string | array<string> | Closure | null $color
*/
public function modalIconColor(string | array | Closure | null $color = null): static
{
$this->modalIconColor = $color;
return $this;
}
public function slideOver(bool | Closure $condition = true): static
{
$this->isModalSlideOver = $condition;
return $this;
}
public function slideOverPosition(SlideOverPosition | Closure | null $position = null): static
{
$this->modalSlideOverPosition = $position;
return $this;
}
/**
* @param array<Action> | Closure | null $actions
*
* @deprecated Use `modalFooterActions()` instead.
*/
public function modalActions(array | Closure | null $actions = null): static
{
$this->modalFooterActions($actions);
return $this;
}
/**
* @param array<Action> | Closure | null $actions
*/
public function modalFooterActions(array | Closure | null $actions = null): static
{
$this->modalFooterActions = $actions;
return $this;
}
public function modalFooterActionsAlignment(Alignment | string | Closure | null $alignment = null): static
{
$this->modalFooterActionsAlignment = $alignment;
return $this;
}
/**
* @param array<Action> | Closure $actions
*
* @deprecated Use `extraModalFooterActions()` instead.
*/
public function extraModalActions(array | Closure $actions): static
{
$this->extraModalFooterActions($actions);
return $this;
}
/**
* @param array<Action | ActionGroup> | Closure $actions
*/
public function extraModalFooterActions(array | Closure $actions): static
{
$this->extraModalFooterActions = $actions;
return $this;
}
/**
* @param array<Action | Closure> $actions
*/
public function registerModalActions(array $actions): static
{
$this->modalActions = [
...$this->modalActions,
...$actions,
];
return $this;
}
public function modalSubmitAction(Action | bool | Closure | null $action = null): static
{
$this->modalSubmitAction = $action;
return $this;
}
public function modalCancelAction(Action | bool | Closure | null $action = null): static
{
$this->modalCancelAction = $action;
return $this;
}
public function modalSubmitActionLabel(string | Closure | null $label = null): static
{
$this->modalSubmitActionLabel = $label;
return $this;
}
public function modalCancelActionLabel(string | Closure | null $label = null): static
{
$this->modalCancelActionLabel = $label;
return $this;
}
/**
* @deprecated Use `modalSubmitActionLabel()` instead.
*/
public function modalButton(string | Closure | null $label = null): static
{
$this->modalSubmitActionLabel($label);
return $this;
}
public function modalContent(View | Htmlable | Closure | null $content = null): static
{
$this->modalContent = $content;
return $this;
}
/**
* @deprecated Use `modalContentFooter()` instead.
*/
public function modalFooter(View | Htmlable | Closure | null $footer = null): static
{
return $this->modalContentFooter($footer);
}
public function modalContentFooter(View | Htmlable | Closure | null $footer = null): static
{
$this->modalContentFooter = $footer;
return $this;
}
public function modalHeading(string | Htmlable | Closure | null $heading = null): static
{
$this->modalHeading = $heading;
return $this;
}
public function modalDescription(string | Htmlable | Closure | null $description = null): static
{
$this->modalDescription = $description;
return $this;
}
/**
* @deprecated Use `modalDescription()` instead.
*/
public function modalSubheading(string | Htmlable | Closure | null $subheading = null): static
{
$this->modalDescription($subheading);
return $this;
}
public function modalWidth(Width | string | Closure | null $width = null): static
{
$this->modalWidth = $width;
return $this;
}
public function getLivewireCallMountedActionName(): ?string
{
return null;
}
public function modal(bool | Closure | null $condition = true): static
{
$this->hasModal = $condition;
return $this;
}
public function modalHidden(bool | Closure | null $condition = true): static
{
$this->isModalHidden = $condition;
return $this;
}
/**
* @return array<string, Action | ActionGroup>
*/
public function getModalFooterActions(): array
{
if ($this->isWizard()) {
return [];
}
if (isset($this->cachedModalFooterActions)) {
return $this->cachedModalFooterActions;
}
if ($this->modalFooterActions !== null) {
$actions = [];
foreach ($this->evaluate($this->modalFooterActions) as $modalAction) {
$actions[$modalAction->getName()] = $this->prepareModalAction($modalAction);
}
return $this->cachedModalFooterActions = $actions;
}
$actions = [];
if ($submitAction = $this->getModalSubmitAction()) {
$actions['submit'] = $submitAction;
}
$actions = [
...$actions,
...$this->getExtraModalFooterActions(),
];
if ($cancelAction = $this->getModalCancelAction()) {
$actions['cancel'] = $cancelAction;
}
if (in_array($this->getModalFooterActionsAlignment(), [Alignment::Center, 'center'])) {
$actions = array_reverse($actions);
}
return $this->cachedModalFooterActions = $actions;
}
public function getModalFooterActionsAlignment(): string | Alignment | null
{
if ($alignment = $this->evaluate($this->modalFooterActionsAlignment)) {
return $alignment;
}
if ($this->isConfirmationRequired()) {
return Alignment::Center;
}
return null;
}
/**
* @return array<string, Action>
*/
public function getModalActions(): array
{
if (isset($this->cachedModalActions)) {
return $this->cachedModalActions;
}
$actions = [];
foreach ($this->getModalFooterActions() as $key => $action) {
if ($action instanceof ActionGroup) {
foreach ($action->getFlatActions() as $flatAction) {
$actions[$flatAction->getName()] = $flatAction;
}
} else {
$actions[$key] = $action;
}
}
foreach ($this->modalActions as $action) {
foreach (Arr::wrap($this->evaluate($action)) as $modalAction) {
$actions[$modalAction->getName()] = $this->prepareModalAction($modalAction);
}
}
return $this->cachedModalActions = $actions;
}
public function getModalAction(string $name): ?Action
{
return $this->getModalActions()[$name] ?? null;
}
public function prepareModalAction(Action $action): Action
{
return $action
->parentAction($this)
->schemaContainer($this->getSchemaContainer())
->schemaComponent($this->getSchemaComponent())
->livewire($this->getLivewire())
->when(
! $action->hasRecord(),
fn (Action $action) => $action->record($this->getRecord()),
)
->table($this->getTable());
}
protected function prepareModalActionGroup(ActionGroup $group): ActionGroup
{
$group
->schemaContainer($this->getSchemaContainer())
->schemaComponent($this->getSchemaComponent())
->livewire($this->getLivewire())
->when(
! $group->hasRecord(),
fn (ActionGroup $group) => $group->record($this->getRecord()),
)
->table($this->getTable());
foreach ($group->getActions() as $nestedAction) {
if ($nestedAction instanceof ActionGroup) {
$this->prepareModalActionGroup($nestedAction);
continue;
}
$this->prepareModalAction($nestedAction);
}
return $group;
}
/**
* @return array<Action | ActionGroup>
*/
public function getVisibleModalFooterActions(): array
{
return array_filter(
$this->getModalFooterActions(),
fn (Action | ActionGroup $action): bool => $action->isVisible(),
);
}
public function getModalSubmitAction(): ?Action
{
$hasFormWrapper = $this->hasFormWrapper();
$action = static::makeModalAction('submit')
->label($this->getModalSubmitActionLabel())
->submit($hasFormWrapper ? $this->getLivewireCallMountedActionName() : null)
->action($hasFormWrapper ? null : $this->getLivewireCallMountedActionName())
->color(match ($color = $this->getColor()) {
'gray' => 'primary',
default => $color,
});
if ($this->modalSubmitAction !== null) {
$action = $this->evaluate($this->modalSubmitAction, ['action' => $action]) ?? $action;
}
if ($action === false) {
return null;
}
return $action;
}
public function getModalCancelAction(): ?Action
{
$action = static::makeModalAction('cancel')
->label($this->getModalCancelActionLabel())
->close()
->color('gray');
if ($this->modalCancelAction !== null) {
$action = $this->evaluate($this->modalCancelAction, ['action' => $action]) ?? $action;
}
if ($action === false) {
return null;
}
return $action;
}
/**
* @return array<Action | ActionGroup>
*/
public function getExtraModalFooterActions(): array
{
if (isset($this->cachedExtraModalFooterActions)) {
return $this->cachedExtraModalFooterActions;
}
$actions = [];
foreach ($this->evaluate($this->extraModalFooterActions) as $action) {
if ($action instanceof ActionGroup) {
$actions[] = $this->prepareModalActionGroup($action);
} else {
$actions[$action->getName()] = $this->prepareModalAction($action);
}
}
return $this->cachedExtraModalFooterActions = $actions;
}
public function getModalAlignment(): Alignment | string
{
if ($alignment = $this->evaluate($this->modalAlignment)) {
return $alignment;
}
if ($this->isConfirmationRequired() || in_array($this->getModalWidth(), [Width::ExtraSmall, Width::Small, 'xs', 'sm'])) {
return Alignment::Center;
}
return Alignment::Start;
}
public function getModalSubmitActionLabel(): string
{
if (filled($label = $this->evaluate($this->modalSubmitActionLabel))) {
return $label;
}
if ($this->isConfirmationRequired()) {
return __('filament-actions::modal.actions.confirm.label');
}
return __('filament-actions::modal.actions.submit.label');
}
public function getModalCancelActionLabel(): string
{
return $this->evaluate($this->modalCancelActionLabel) ?? __('filament-actions::modal.actions.cancel.label');
}
public function getModalContent(): View | Htmlable | null
{
return $this->evaluate($this->modalContent);
}
public function getModalContentFooter(): View | Htmlable | null
{
return $this->evaluate($this->modalContentFooter);
}
public function hasModalContent(): bool
{
return $this->modalContent !== null;
}
public function hasModalContentFooter(): bool
{
return $this->modalContentFooter !== null;
}
public function getCustomModalHeading(): string | Htmlable | null
{
return $this->evaluate($this->modalHeading);
}
public function getModalHeading(): string | Htmlable
{
return $this->getCustomModalHeading() ?? $this->getLabel();
}
public function hasCustomModalHeading(): bool
{
return filled($this->getCustomModalHeading());
}
public function getModalDescription(): string | Htmlable | null
{
if (filled($description = $this->evaluate($this->modalDescription))) {
return $description;
}
if ($this->isConfirmationRequired()) {
return __('filament-actions::modal.confirmation');
}
return null;
}
public function hasModalDescription(): bool
{
return filled($this->getModalDescription());
}
public function getModalWidth(): Width | string
{
if ($width = $this->evaluate($this->modalWidth)) {
return $width;
}
if ($this->isConfirmationRequired()) {
return Width::Medium;
}
return Width::FourExtraLarge;
}
public function isModalFooterSticky(): bool
{
return (bool) ($this->evaluate($this->isModalFooterSticky) ?? $this->isModalSlideOver());
}
public function isModalHeaderSticky(): bool
{
return (bool) ($this->evaluate($this->isModalHeaderSticky) ?? $this->isModalSlideOver());
}
public function isModalSlideOver(): bool
{
return (bool) $this->evaluate($this->isModalSlideOver);
}
public function getModalSlideOverPosition(): ?SlideOverPosition
{
return $this->evaluate($this->modalSlideOverPosition);
}
public function hasModal(): ?bool
{
return $this->evaluate($this->hasModal);
}
public function shouldOpenModal(?Closure $checkForSchemaUsing = null): bool
{
if (is_bool($hasModal = $this->hasModal())) {
return $hasModal;
}
if ($this->evaluate($this->isModalHidden)) {
return false;
}
return $this->hasCustomModalHeading() ||
$this->hasModalDescription() ||
$this->hasModalContent() ||
$this->hasModalContentFooter() ||
(value($checkForSchemaUsing, $this) ?? false);
}
public function isModalClickThrough(): bool
{
return (bool) $this->evaluate($this->isModalClickThrough);
}
public function hasModalCloseButton(): bool
{
return $this->evaluate($this->hasModalCloseButton) ?? ModalComponent::$hasCloseButton;
}
public function isModalClosedByClickingAway(): bool
{
return (bool) ($this->evaluate($this->isModalClosedByClickingAway) ?? ModalComponent::$isClosedByClickingAway);
}
public function isModalClosedByEscaping(): bool
{
return (bool) ($this->evaluate($this->isModalClosedByEscaping) ?? ModalComponent::$isClosedByEscaping);
}
public function isModalAutofocused(): bool
{
return $this->evaluate($this->isModalAutofocused) ?? ModalComponent::$isAutofocused;
}
public function hasUnsavedChangesAlert(): bool
{
return (bool) ($this->evaluate($this->hasUnsavedChangesAlert) ?? (! $this->isSchemaDisabled()));
}
/**
* @deprecated Use `makeModalSubmitAction()` instead.
*
* @param array<string, mixed> | null $arguments
*/
public function makeExtraModalAction(string $name, ?array $arguments = null): Action
{
return $this->makeModalSubmitAction($name, $arguments);
}
/**
* @param array<string, mixed> | null $arguments
*/
public function makeModalSubmitAction(string $name, ?array $arguments = null): Action
{
return static::makeModalAction($name)
->callParent($this->getLivewireCallMountedActionName())
->arguments($arguments)
->color('gray');
}
public function makeModalAction(string $name): Action
{
return Action::make($name)
->button();
}
public function getModalIcon(): string | BackedEnum | Htmlable | null
{
if ($icon = $this->evaluate($this->modalIcon)) {
return $icon;
}
if ($this->isConfirmationRequired()) {
return FilamentIcon::resolve(ActionsIconAlias::MODAL_CONFIRMATION) ?? Heroicon::OutlinedExclamationTriangle;
}
return null;
}
/**
* @return string | array<string> | null
*/
public function getModalIconColor(): string | array | null
{
return $this->evaluate($this->modalIconColor) ?? $this->getColor() ?? 'primary';
}
public function stickyModalFooter(bool | Closure $condition = true): static
{
$this->isModalFooterSticky = $condition;
return $this;
}
public function stickyModalHeader(bool | Closure $condition = true): static
{
$this->isModalHeaderSticky = $condition;
return $this;
}
public function hasCustomModalPresence(): bool
{
return $this->hasModal !== null;
}
}

View file

@ -0,0 +1,77 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
trait CanOpenUrl
{
protected bool | Closure $shouldOpenUrlInNewTab = false;
protected string | Closure | null $url = null;
protected bool | Closure $shouldPostToUrl = false;
public function openUrlInNewTab(bool | Closure $condition = true): static
{
$this->shouldOpenUrlInNewTab = $condition;
return $this;
}
public function url(string | Closure | null $url, bool | Closure | null $shouldOpenInNewTab = null): static
{
// Security: If this URL is derived from user input, validate it
// to prevent XSS via `javascript:` or `data:` protocol URLs
// rendered in `href` attributes.
if ($shouldOpenInNewTab !== null) {
$this->openUrlInNewTab($shouldOpenInNewTab);
}
$this->url = $url;
return $this;
}
public function postToUrl(bool | Closure $condition = true): static
{
$this->shouldPostToUrl = $condition;
return $this;
}
public function getUrl(): ?string
{
if ($this->hasModal()) {
return null;
}
return $this->evaluate($this->url) ?? $this->getHasActionsLivewire()?->getDefaultActionUrl($this);
}
public function shouldOpenUrlInNewTab(): bool
{
return (bool) $this->evaluate($this->shouldOpenUrlInNewTab);
}
public function shouldPostToUrl(): bool
{
return (bool) $this->evaluate($this->shouldPostToUrl);
}
public function hasUrl(): bool
{
return $this->url !== null;
}
public function hasShouldOpenUrlInNewTab(): bool
{
return $this->shouldOpenUrlInNewTab !== false;
}
public function hasShouldPostToUrl(): bool
{
return $this->shouldPostToUrl !== false;
}
}

View file

@ -0,0 +1,56 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
use Filament\Support\Facades\FilamentView;
trait CanRedirect
{
protected string | Closure | null $failureRedirectUrl = null;
protected string | Closure | null $successRedirectUrl = null;
public function dispatchFailureRedirect(): static
{
$url = $this->evaluate($this->failureRedirectUrl) ?? $this->getHasActionsLivewire()->getDefaultActionFailureRedirectUrl($this);
if (filled($url)) {
$this->redirect($url);
}
return $this;
}
public function dispatchSuccessRedirect(): static
{
$url = $this->evaluate($this->successRedirectUrl) ?? $this->getHasActionsLivewire()->getDefaultActionSuccessRedirectUrl($this);
if (filled($url)) {
$this->redirect($url);
}
return $this;
}
public function redirect(string | Closure $url, ?bool $navigate = null): void
{
$url = $this->evaluate($url);
$this->getLivewire()->redirect($url, navigate: $navigate ?? FilamentView::hasSpaMode($url));
}
public function failureRedirectUrl(string | Closure | null $url): static
{
$this->failureRedirectUrl = $url;
return $this;
}
public function successRedirectUrl(string | Closure | null $url): static
{
$this->successRedirectUrl = $url;
return $this;
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
trait CanRequireConfirmation
{
protected bool | Closure $isConfirmationRequired = false;
public function requiresConfirmation(bool | Closure $condition = true): static
{
$this->isConfirmationRequired = $condition;
return $this;
}
public function isConfirmationRequired(): bool
{
return $this->isConfirmationRequired = ((bool) $this->evaluate($this->isConfirmationRequired));
}
}

View file

@ -0,0 +1,52 @@
<?php
namespace Filament\Actions\Concerns;
trait CanSubmitForm
{
protected bool $canSubmitForm = false;
protected ?string $formToSubmit = null;
protected ?string $formId = null;
public function submit(?string $form): static
{
$this->canSubmitForm = filled($form);
$this->formToSubmit = $form;
return $this;
}
public function canSubmitForm(): bool
{
return $this->canSubmitForm;
}
public function getFormToSubmit(): ?string
{
return $this->formToSubmit;
}
public function formId(?string $id): static
{
$this->formId = $id;
return $this;
}
public function getFormId(): ?string
{
return $this->formId;
}
public function hasCanSubmitForm(): bool
{
return $this->canSubmitForm;
}
public function hasFormId(): bool
{
return $this->formId !== null;
}
}

View file

@ -0,0 +1,50 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
use Illuminate\Support\Facades\DB;
trait CanUseDatabaseTransactions
{
protected bool | Closure $hasDatabaseTransactions = false;
public function databaseTransaction(bool | Closure $condition = true): static
{
$this->hasDatabaseTransactions = $condition;
return $this;
}
public function hasDatabaseTransactions(): bool
{
return (bool) $this->evaluate($this->hasDatabaseTransactions);
}
public function beginDatabaseTransaction(): void
{
if (! $this->hasDatabaseTransactions()) {
return;
}
DB::beginTransaction();
}
public function commitDatabaseTransaction(): void
{
if (! $this->hasDatabaseTransactions()) {
return;
}
DB::commit();
}
public function rollBackDatabaseTransaction(): void
{
if (! $this->hasDatabaseTransactions()) {
return;
}
DB::rollBack();
}
}

View file

@ -0,0 +1,57 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
trait HasAction
{
protected Closure | string | null $action = null;
protected bool | Closure | null $isLivewireClickHandlerEnabled = null;
public function action(Closure | string | null $action): static
{
$this->action = $action;
return $this;
}
public function livewireClickHandlerEnabled(bool | Closure | null $condition = true): static
{
$this->isLivewireClickHandlerEnabled = $condition;
return $this;
}
public function getActionFunction(): ?Closure
{
if (! $this->action instanceof Closure) {
return null;
}
return $this->action;
}
public function isLivewireClickHandlerEnabled(): bool
{
if (($isLivewireClickHandlerEnabled = $this->evaluate($this->isLivewireClickHandlerEnabled)) !== null) {
return (bool) $isLivewireClickHandlerEnabled;
}
if (filled($this->getUrl())) {
return false;
}
if ($this->canSubmitForm()) {
return false;
}
return true;
}
public function hasAction(): bool
{
return $this->action !== null;
}
}

View file

@ -0,0 +1,61 @@
<?php
namespace Filament\Actions\Concerns;
trait HasArguments
{
/**
* @var array<string, mixed> | null
*/
protected ?array $arguments = null;
/**
* @param array<string, mixed> | null $arguments
*/
public function arguments(?array $arguments): static
{
if ($arguments === null) {
$this->arguments = null;
return $this;
}
$this->arguments = [];
$this->mergeArguments($arguments);
return $this;
}
/**
* @param array<string, mixed> $arguments
*/
public function mergeArguments(array $arguments): static
{
$this->arguments = [
...$this->arguments ?? [],
...$arguments,
];
return $this;
}
/**
* @return array<string, mixed>
*/
public function getArguments(): array
{
return $this->arguments ?? [];
}
public function resetArguments(): static
{
$this->arguments(null);
return $this;
}
public function hasArguments(): bool
{
return $this->arguments !== null;
}
}

View file

@ -0,0 +1,113 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
trait HasData
{
/**
* @var array<string, mixed>
*/
protected array $data = [];
protected ?Closure $mutateDataUsing = null;
public function mutateDataUsing(?Closure $callback): static
{
$this->mutateDataUsing = $callback;
return $this;
}
/**
* @deprecated Use `mutateDataUsing()` instead.
*/
public function mutateFormDataUsing(?Closure $callback): static
{
$this->mutateDataUsing($callback);
return $this;
}
/**
* @param array<string, mixed> $data
*/
public function data(array $data, bool $shouldMutate = true): static
{
if ($shouldMutate && $this->mutateDataUsing) {
$data = $this->evaluate($this->mutateDataUsing, [
'data' => $data,
]);
}
$this->data = $data;
return $this;
}
/**
* @deprecated Use `data()` instead.
*
* @param array<string, mixed> $data
*/
public function formData(array $data, bool $shouldMutate = true): static
{
$this->data($data, $shouldMutate);
return $this;
}
public function resetData(): static
{
$this->data([], shouldMutate: false);
return $this;
}
/**
* @deprecated Use `resetData()` instead.
*/
public function resetFormData(): static
{
$this->resetData();
return $this;
}
/**
* @return array<string, mixed>
*/
public function getData(): array
{
return $this->data;
}
/**
* @deprecated Use `getData()` instead.
*
* @return array<string, mixed>
*/
public function getFormData(): array
{
return $this->getData();
}
/**
* @return array<string, mixed>
*/
public function getRawData(): array
{
return $this->getLivewire()->mountedActions[$this->getNestingIndex()]['data'] ?? [];
}
/**
* @deprecated Use `getRawData()` instead.
*
* @return array<string, mixed>
*/
public function getRawFormData(): array
{
return $this->getRawData();
}
}

View file

@ -0,0 +1,139 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
use Filament\Support\Enums\Width;
trait HasDropdown
{
protected bool | Closure $hasDropdown = true;
protected string | Closure | null $dropdownPlacement = null;
protected string | Closure | null $defaultDropdownPlacement = null;
protected string | Closure | null $dropdownMaxHeight = null;
protected int | Closure | null $dropdownOffset = null;
protected Width | string | Closure | null $dropdownWidth = null;
protected bool | Closure $hasDropdownFlip = true;
protected bool | Closure | null $hasDropdownTeleport = null;
protected bool | Closure | null $hasDefaultDropdownTeleport = null;
public function dropdown(bool | Closure $condition = true): static
{
$this->hasDropdown = $condition;
return $this;
}
public function dropdownPlacement(string | Closure | null $placement): static
{
$this->dropdownPlacement = $placement;
return $this;
}
public function dropdownAutoPlacement(): static
{
$this->dropdownPlacement('auto-placement');
$this->dropdownFlip(false);
return $this;
}
public function defaultDropdownPlacement(string | Closure | null $placement): static
{
$this->defaultDropdownPlacement = $placement;
return $this;
}
public function dropdownMaxHeight(string | Closure | null $height): static
{
$this->dropdownMaxHeight = $height;
return $this;
}
public function dropdownOffset(int | Closure | null $offset): static
{
$this->dropdownOffset = $offset;
return $this;
}
public function dropdownWidth(Width | string | Closure | null $width): static
{
$this->dropdownWidth = $width;
return $this;
}
public function dropdownFlip(bool | Closure $condition = true): static
{
$this->hasDropdownFlip = $condition;
return $this;
}
public function dropdownTeleport(bool | Closure | null $condition = true): static
{
$this->hasDropdownTeleport = $condition;
return $this;
}
public function defaultDropdownTeleport(bool | Closure | null $condition = true): static
{
$this->hasDefaultDropdownTeleport = $condition;
return $this;
}
public function getDropdownPlacement(): ?string
{
return $this->evaluate($this->dropdownPlacement) ?? $this->evaluate($this->defaultDropdownPlacement);
}
public function getDropdownMaxHeight(): ?string
{
return $this->evaluate($this->dropdownMaxHeight);
}
public function getDropdownOffset(): ?int
{
return $this->evaluate($this->dropdownOffset);
}
public function getDropdownWidth(): Width | string | null
{
$width = $this->evaluate($this->dropdownWidth);
if (is_string($width)) {
$width = Width::tryFrom($width) ?? $width;
}
return $width;
}
public function hasDropdownFlip(): bool
{
return (bool) $this->evaluate($this->hasDropdownFlip);
}
public function hasDropdownTeleport(): bool
{
return (bool) ($this->evaluate($this->hasDropdownTeleport) ?? $this->evaluate($this->hasDefaultDropdownTeleport));
}
public function hasDropdown(): bool
{
return (bool) $this->evaluate($this->hasDropdown);
}
}

View file

@ -0,0 +1,52 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
use Filament\Support\View\ComponentAttributeBag as FilamentComponentAttributeBag;
use Illuminate\View\ComponentAttributeBag;
trait HasExtraModalOverlayAttributes
{
/**
* @var array<array<mixed> | Closure>
*/
protected array $extraModalOverlayAttributes = [];
/**
* @param array<mixed> | Closure $attributes
*/
public function extraModalOverlayAttributes(array | Closure $attributes, bool $merge = false): static
{
if ($merge) {
if (($attributes instanceof Closure) && in_array($attributes, $this->extraModalOverlayAttributes, strict: true)) {
return $this;
}
$this->extraModalOverlayAttributes[] = $attributes;
} else {
$this->extraModalOverlayAttributes = [$attributes];
}
return $this;
}
/**
* @return array<mixed>
*/
public function getExtraModalOverlayAttributes(): array
{
$temporaryAttributeBag = new FilamentComponentAttributeBag;
foreach ($this->extraModalOverlayAttributes as $extraModalOverlayAttributes) {
$temporaryAttributeBag = $temporaryAttributeBag->merge($this->evaluate($extraModalOverlayAttributes), escape: false);
}
return $temporaryAttributeBag->getAttributes();
}
public function getExtraModalOverlayAttributeBag(): ComponentAttributeBag
{
return new FilamentComponentAttributeBag($this->getExtraModalOverlayAttributes());
}
}

View file

@ -0,0 +1,55 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
use Filament\Support\View\ComponentAttributeBag as FilamentComponentAttributeBag;
use Illuminate\View\ComponentAttributeBag;
trait HasExtraModalWindowAttributes
{
/**
* @var array<array<mixed> | Closure>
*/
protected array $extraModalWindowAttributes = [];
/**
* @param array<mixed> | Closure $attributes
*/
public function extraModalWindowAttributes(array | Closure $attributes, bool $merge = false): static
{
// Security: Attribute values are not escaped when rendered. Never
// pass unsanitized user input as attribute names or values.
if ($merge) {
if (($attributes instanceof Closure) && in_array($attributes, $this->extraModalWindowAttributes, strict: true)) {
return $this;
}
$this->extraModalWindowAttributes[] = $attributes;
} else {
$this->extraModalWindowAttributes = [$attributes];
}
return $this;
}
/**
* @return array<mixed>
*/
public function getExtraModalWindowAttributes(): array
{
$temporaryAttributeBag = new FilamentComponentAttributeBag;
foreach ($this->extraModalWindowAttributes as $extraModalWindowAttributes) {
$temporaryAttributeBag = $temporaryAttributeBag->merge($this->evaluate($extraModalWindowAttributes), escape: false);
}
return $temporaryAttributeBag->getAttributes();
}
public function getExtraModalWindowAttributeBag(): ComponentAttributeBag
{
return new FilamentComponentAttributeBag($this->getExtraModalWindowAttributes());
}
}

View file

@ -0,0 +1,29 @@
<?php
namespace Filament\Actions\Concerns;
use BackedEnum;
use Closure;
use Illuminate\Contracts\Support\Htmlable;
trait HasGroupedIcon
{
protected string | BackedEnum | Htmlable | Closure | null $groupedIcon = null;
public function groupedIcon(string | BackedEnum | Htmlable | Closure | null $icon): static
{
$this->groupedIcon = $icon;
return $this;
}
public function getGroupedIcon(): string | BackedEnum | Htmlable | null
{
return $this->evaluate($this->groupedIcon);
}
public function hasGroupedIcon(): bool
{
return $this->groupedIcon !== null;
}
}

View file

@ -0,0 +1,20 @@
<?php
namespace Filament\Actions\Concerns;
trait HasId
{
protected ?string $id = null;
public function id(string $id): static
{
$this->id = $id;
return $this;
}
public function getId(): string
{
return $this->id ?? $this->getName();
}
}

View file

@ -0,0 +1,23 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Schemas\Components\Component;
trait HasInfolist
{
/**
* @deprecated Use `schema() instead.
*
* @param array<Component | Action | ActionGroup> | Closure | null $infolist
*/
public function infolist(array | Closure | null $infolist): static
{
$this->schema($infolist);
return $this;
}
}

View file

@ -0,0 +1,39 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
use Illuminate\Support\Arr;
trait HasKeyBindings
{
/**
* @var string | array<string> | Closure | null
*/
protected string | array | Closure | null $keyBindings = null;
/**
* @param string | array<string> | Closure | null $bindings
*/
public function keyBindings(string | array | Closure | null $bindings): static
{
$this->keyBindings = $bindings;
return $this;
}
/**
* @return array<string> | null
*/
public function getKeyBindings(): ?array
{
$keyBindings = Arr::wrap($this->evaluate($this->keyBindings));
return count($keyBindings) ? $keyBindings : null;
}
public function hasKeyBindings(): bool
{
return $this->keyBindings !== null;
}
}

View file

@ -0,0 +1,69 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
use Illuminate\Contracts\Support\Htmlable;
trait HasLabel
{
protected string | Htmlable | Closure | null $label = null;
protected bool | Closure $isLabelHidden = false;
protected bool $shouldTranslateLabel = false;
/**
* @deprecated Use `hiddenLabel()` instead.
*/
public function disableLabel(bool | Closure $condition = true): static
{
$this->hiddenLabel($condition);
return $this;
}
public function hiddenLabel(bool | Closure $condition = true): static
{
$this->isLabelHidden = $condition;
return $this;
}
public function label(string | Htmlable | Closure | null $label): static
{
$this->label = $label;
return $this;
}
public function translateLabel(bool $shouldTranslateLabel = true): static
{
$this->shouldTranslateLabel = $shouldTranslateLabel;
return $this;
}
public function getLabel(): string | Htmlable | null
{
$label = $this->evaluate($this->label) ?? (string) str($this->getName())
->before('.')
->kebab()
->replace(['-', '_'], ' ')
->ucfirst();
return is_string($label) && $this->shouldTranslateLabel
? __($label)
: $label;
}
public function isLabelHidden(): bool
{
return (bool) $this->evaluate($this->isLabelHidden);
}
public function hasLabelHidden(): bool
{
return $this->isLabelHidden !== false;
}
}

View file

@ -0,0 +1,101 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
use Filament\Actions\Events\ActionCalled;
use Filament\Actions\Events\ActionCalling;
use Illuminate\Support\Facades\Event;
trait HasLifecycleHooks
{
protected ?Closure $before = null;
protected ?Closure $after = null;
protected ?Closure $beforeFormFilled = null;
protected ?Closure $afterFormFilled = null;
protected ?Closure $beforeFormValidated = null;
protected ?Closure $afterFormValidated = null;
public function before(?Closure $callback): static
{
$this->before = $callback;
return $this;
}
public function after(?Closure $callback): static
{
$this->after = $callback;
return $this;
}
public function beforeFormFilled(?Closure $callback): static
{
$this->beforeFormFilled = $callback;
return $this;
}
public function afterFormFilled(?Closure $callback): static
{
$this->afterFormFilled = $callback;
return $this;
}
public function beforeFormValidated(?Closure $callback): static
{
$this->beforeFormValidated = $callback;
return $this;
}
public function afterFormValidated(?Closure $callback): static
{
$this->afterFormValidated = $callback;
return $this;
}
public function callBefore(): mixed
{
Event::dispatch(ActionCalling::class, $this);
return $this->evaluate($this->before);
}
public function callAfter(): mixed
{
try {
return $this->evaluate($this->after);
} finally {
Event::dispatch(ActionCalled::class, $this);
}
}
public function callBeforeFormFilled(): mixed
{
return $this->evaluate($this->beforeFormFilled);
}
public function callAfterFormFilled(): mixed
{
return $this->evaluate($this->afterFormFilled);
}
public function callBeforeFormValidated(): mixed
{
return $this->evaluate($this->beforeFormValidated);
}
public function callAfterFormValidated(): mixed
{
return $this->evaluate($this->afterFormValidated);
}
}

View file

@ -0,0 +1,35 @@
<?php
namespace Filament\Actions\Concerns;
trait HasMountableArguments
{
/**
* @var array<string, mixed>|null
*/
protected ?array $invokedArguments = null;
/**
* @param array<string, mixed> $arguments
*/
public function __invoke(array $arguments): static
{
// Clone the action so that we don't accidentally mutate
// the cached action's arguments while rendering it,
// especially if it's mounted with different arguments.
$action = clone $this;
$action->arguments($arguments);
$action->invokedArguments = $arguments;
return $action;
}
/**
* @return array<string, mixed>|null
*/
public function getInvokedArguments(): ?array
{
return $this->invokedArguments;
}
}

View file

@ -0,0 +1,28 @@
<?php
namespace Filament\Actions\Concerns;
use LogicException;
trait HasName
{
protected ?string $name = null;
public function name(?string $name): static
{
$this->name = $name;
return $this;
}
public function getName(): ?string
{
if (blank($this->name)) {
$actionClass = static::class;
throw new LogicException("Action of class [$actionClass] must have a unique name, passed to the [make()] method.");
}
return $this->name;
}
}

View file

@ -0,0 +1,76 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
trait HasParentActions
{
protected bool | string | Closure | null $cancelParentActions = null;
protected bool | string | Closure | null $cancelParentActionsOnClose = null;
protected bool | Closure $shouldOverlayParentActions = false;
public function cancelParentActions(bool | string | Closure | null $toAction = true): static
{
$this->cancelParentActions = $toAction;
return $this;
}
public function cancelParentActionsOnClose(bool | string | Closure | null $toAction = true): static
{
$this->cancelParentActionsOnClose = $toAction;
return $this;
}
public function overlayParentActions(bool | Closure $condition = true): static
{
$this->shouldOverlayParentActions = $condition;
return $this;
}
public function shouldCancelAllParentActions(): bool
{
return $this->evaluate($this->cancelParentActions) === true;
}
public function getParentActionToCancelTo(): ?string
{
$toAction = $this->evaluate($this->cancelParentActions);
return is_string($toAction) ? $toAction : null;
}
public function getParentActionsToCancelOnClose(): bool | string
{
$toAction = $this->evaluate($this->cancelParentActionsOnClose);
return is_string($toAction) ? $toAction : ($toAction === true);
}
public function shouldCancelParentActionsOnClose(): bool
{
return $this->getParentActionsToCancelOnClose() !== false;
}
public function shouldCancelAllParentActionsOnClose(): bool
{
return $this->getParentActionsToCancelOnClose() === true;
}
public function getParentActionToCancelToOnClose(): ?string
{
$toAction = $this->getParentActionsToCancelOnClose();
return is_string($toAction) ? $toAction : null;
}
public function shouldOverlayParentActions(): bool
{
return (bool) $this->evaluate($this->shouldOverlayParentActions);
}
}

View file

@ -0,0 +1,150 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Schemas\Components\Component;
use Filament\Schemas\Components\Wizard;
use Filament\Schemas\Schema;
trait HasSchema
{
/**
* @var array<Component | Action | ActionGroup> | Closure | null
*/
protected array | Closure | null $schema = null;
protected bool | Closure $isSchemaDisabled = false;
protected bool | Closure | null $hasFormWrapper = null;
/**
* @param array<Component | Action | ActionGroup> | Closure | null $schema
*/
public function schema(array | Closure | null $schema): static
{
$this->schema = $schema;
return $this;
}
public function disabledSchema(bool | Closure $condition = true): static
{
$this->isSchemaDisabled = $condition;
return $this;
}
public function isSchemaDisabled(): bool
{
return (bool) $this->evaluate($this->isSchemaDisabled);
}
public function getSchema(Schema $schema): ?Schema
{
$modifiedSchema = $this->evaluate($this->schema ?? $this->getHasActionsLivewire()?->getDefaultActionSchemaResolver($this), [
'form' => $schema,
'schema' => $schema,
'infolist' => $schema,
]);
if ($modifiedSchema === null) {
return null;
}
if (is_array($modifiedSchema) && (! count($modifiedSchema))) {
return null;
}
if (is_array($modifiedSchema) && $this->isWizard()) {
$wizard = Wizard::make($modifiedSchema)
->contained(false)
->startOnStep($this->getWizardStartStep())
->cancelAction($this->getModalCancelAction())
->submitAction($this->getModalSubmitAction())
->alpineSubmitHandler("\$wire.{$this->getLivewireCallMountedActionName()}()")
->skippable($this->isWizardSkippable())
->disabled($this->isSchemaDisabled());
if ($this->modifyWizardUsing) {
$wizard = $this->evaluate($this->modifyWizardUsing, [
'wizard' => $wizard,
]) ?? $wizard;
}
$modifiedSchema = [$wizard];
}
if (is_array($modifiedSchema)) {
$modifiedSchema = $schema->components($modifiedSchema);
}
if ($this->isSchemaDisabled()) {
return $modifiedSchema->disabled();
}
return $modifiedSchema;
}
public function formWrapper(bool | Closure | null $condition = true): static
{
$this->hasFormWrapper = $condition;
return $this;
}
public function hasFormWrapper(): bool
{
return (bool) ($this->evaluate($this->hasFormWrapper) ?? (! $this->isWizard()));
}
/**
* @deprecated Use `disabledSchema() instead.
*/
public function disableForm(bool | Closure $condition = true): static
{
$this->disabledSchema($condition);
return $this;
}
/**
* @deprecated Use `disabledSchema() instead.
*/
public function disabledForm(bool | Closure $condition = true): static
{
$this->disabledSchema($condition);
return $this;
}
/**
* @deprecated Use `schema() instead.
*
* @param array<Component| Action> | Closure | null $form
*/
public function form(array | Closure | null $form): static
{
$this->schema($form);
return $this;
}
/**
* @deprecated Use `getSchema()` instead.
*/
public function getForm(Schema $schema): ?Schema
{
return $this->getSchema($schema);
}
/**
* @deprecated Use `isSchemaDisabled()` instead.
*/
public function isFormDisabled(): bool
{
return $this->isSchemaDisabled();
}
}

View file

@ -0,0 +1,47 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
use Filament\Support\Enums\Size;
trait HasSize
{
protected Size | string | Closure | null $defaultSize = null;
protected Size | string | Closure | null $size = null;
public function defaultSize(Size | string | Closure | null $size): static
{
$this->defaultSize = $size;
return $this;
}
public function size(Size | string | Closure | null $size): static
{
$this->size = $size;
return $this;
}
public function getDefaultSize(): Size | string | null
{
return $this->evaluate($this->defaultSize);
}
public function getSize(): Size | string | null
{
return $this->evaluate($this->size) ?? $this->getDefaultSize();
}
public function hasSize(): bool
{
return $this->size !== null || $this->defaultSize !== null;
}
public function hasSmallSizeDefault(): bool
{
return $this->size === null && $this->defaultSize === Size::Small;
}
}

View file

@ -0,0 +1,29 @@
<?php
namespace Filament\Actions\Concerns;
use BackedEnum;
use Closure;
use Illuminate\Contracts\Support\Htmlable;
trait HasTableIcon
{
protected string | BackedEnum | Htmlable | Closure | null $tableIcon = null;
public function tableIcon(string | BackedEnum | Htmlable | Closure | null $icon): static
{
$this->tableIcon = $icon;
return $this;
}
public function getTableIcon(): string | BackedEnum | Htmlable | null
{
return $this->evaluate($this->tableIcon);
}
public function hasTableIcon(): bool
{
return $this->tableIcon !== null;
}
}

View file

@ -0,0 +1,36 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
use Illuminate\Contracts\Support\Htmlable;
trait HasTooltip
{
protected string | Htmlable | Closure | null $tooltip = null;
public function tooltip(string | Htmlable | Closure | null $tooltip): static
{
$this->tooltip = $tooltip;
return $this;
}
public function getTooltip(): string | Htmlable | null
{
if (
$this->hasAuthorizationTooltip() &&
($response = $this->getAuthorizationResponseWithMessage())->denied() &&
filled($responseMessage = $response->message())
) {
return $responseMessage;
}
return $this->evaluate($this->tooltip);
}
public function hasTooltip(): bool
{
return $this->tooltip !== null;
}
}

View file

@ -0,0 +1,65 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
use Filament\Schemas\Components\Wizard\Step;
trait HasWizard
{
protected bool $isWizard = false;
protected bool | Closure $isWizardSkippable = false;
protected int | Closure $wizardStartStep = 1;
protected ?Closure $modifyWizardUsing = null;
/**
* @param array<Step> | Closure $steps
*/
public function steps(array | Closure $steps): static
{
$this->isWizard = true;
$this->schema($steps);
return $this;
}
public function startOnStep(int | Closure $startStep): static
{
$this->wizardStartStep = $startStep;
return $this;
}
public function skippableSteps(bool | Closure $condition = true): static
{
$this->isWizardSkippable = $condition;
return $this;
}
public function isWizard(): bool
{
return $this->isWizard;
}
public function isWizardSkippable(): bool
{
return (bool) $this->evaluate($this->isWizardSkippable);
}
public function modifyWizardUsing(?Closure $callback): static
{
$this->isWizard = true;
$this->modifyWizardUsing = $callback;
return $this;
}
public function getWizardStartStep(): int
{
return $this->evaluate($this->wizardStartStep);
}
}

View file

@ -0,0 +1,974 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
use DanHarrin\LivewireRateLimiting\Exceptions\TooManyRequestsException;
use DanHarrin\LivewireRateLimiting\WithRateLimiting;
use Filament\Actions\Action;
use Filament\Actions\Enums\ActionStatus;
use Filament\Actions\Exceptions\ActionNotResolvableException;
use Filament\Schemas\Components\Contracts\ExposesStateToActionData;
use Filament\Schemas\Concerns\InteractsWithSchemas;
use Filament\Schemas\Contracts\HasSchemas;
use Filament\Schemas\Schema;
use Filament\Support\Exceptions\Cancel;
use Filament\Support\Exceptions\Halt;
use Filament\Support\Livewire\Partials\PartialsComponentHook;
use Filament\Tables\Contracts\HasTable;
use Illuminate\Auth\Access\Response;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Arr;
use Illuminate\Validation\ValidationException;
use Livewire\Attributes\Url;
use ReflectionMethod;
use ReflectionNamedType;
use ReflectionUnionType;
use Throwable;
use function Livewire\store;
trait InteractsWithActions /** @phpstan-ignore trait.unused */
{
use WithRateLimiting;
/**
* @var array<array<string, mixed>> | null
*/
public ?array $mountedActions = [];
protected ?int $originallyMountedActionIndex = null;
protected int $mountActionNestingLevel = 0;
/**
* @var mixed
*/
#[Url(as: 'action')]
public $defaultAction = null;
/**
* @var mixed
*/
#[Url(as: 'actionArguments')]
public $defaultActionArguments = null;
/**
* @var mixed
*/
#[Url(as: 'actionContext')]
public $defaultActionContext = null;
/**
* @var mixed
*/
#[Url(as: 'tableAction')]
public $defaultTableAction = null;
/**
* @var mixed
*/
#[Url(as: 'tableActionRecord')]
public $defaultTableActionRecord = null;
/**
* @var mixed
*/
#[Url(as: 'tableActionArguments')]
public $defaultTableActionArguments = null;
/**
* @var array<string, Action>
*/
protected array $cachedActions = [];
/**
* @var array<Action> | null
*/
protected ?array $cachedMountedActions = null;
protected bool $hasActionsModalRendered = false;
/**
* Context for the `mountAction()` call that opens the `?action=` default action on
* page load. `mountedFromUrl` is forced on last, so a crafted `?actionContext=` value
* cannot unset it to run a modal-less action.
*
* @return array<string, mixed>
*/
public function getDefaultActionUrlContext(): array
{
return array_merge(
is_array($this->defaultActionContext) ? $this->defaultActionContext : [],
['mountedFromUrl' => true],
);
}
/**
* @return array<string, mixed>
*/
public function getDefaultTableActionUrlContext(): array
{
return [
'table' => true,
'recordKey' => $this->defaultTableActionRecord,
'mountedFromUrl' => true,
];
}
public function bootedInteractsWithActions(): void
{
if (filled($originallyMountedActionIndex = array_key_last($this->mountedActions))) {
$this->originallyMountedActionIndex = $originallyMountedActionIndex;
}
$this->cacheTraitActions();
// Boot the InteractsWithTable trait first so the table object is available.
if (! ($this instanceof HasTable)) {
if (empty($this->cacheMountedActions($this->mountedActions))) {
$this->mountedActions = [];
}
}
}
/**
* @param array<string, mixed> $arguments
* @param array<string, mixed> $context
*/
public function mountAction(string $name, array $arguments = [], array $context = []): mixed
{
$this->mountActionNestingLevel++;
try {
$this->mountedActions[] = [
'name' => $name,
'arguments' => $arguments,
'context' => $context,
];
try {
$action = $this->getMountedAction();
} catch (ActionNotResolvableException $exception) {
$action = null;
}
if (! $action) {
$this->unmountAction(cancelParentActions: false);
return null;
}
if ($action->isDisabled()) {
$this->unmountAction(cancelParentActions: false);
return null;
}
if (($actionComponent = $action->getSchemaComponent()) instanceof ExposesStateToActionData) {
foreach ($actionComponent->getChildSchemas() as $actionComponentChildSchema) {
$actionComponentChildSchema->validate();
}
}
// Keep a reference to this entry since the action's mount lifecycle may replace it.
$mountedActionState = &$this->mountedActions[$action->getNestingIndex()];
try {
if (
$action->hasAuthorizationNotification() &&
($response = $action->getAuthorizationResponseWithMessage())->denied()
) {
$action->sendUnauthorizedNotification($response);
throw new Cancel;
}
$hasSchema = $this->mountedActionHasSchema(mountedAction: $action);
if ($hasSchema) {
$action->callBeforeFormFilled();
}
$schema = $this->getMountedActionSchema(mountedAction: $action);
$action->mount([
'form' => $schema,
'schema' => $schema,
]);
if ($hasSchema) {
$action->callAfterFormFilled();
}
} catch (Halt $exception) {
$this->unmountAction(cancelParentActions: false);
return null;
} catch (Cancel $exception) {
$this->unmountAction(cancelParentActions: false);
return null;
} catch (ValidationException $exception) {
$this->unmountAction(cancelParentActions: false);
throw $exception;
}
$mountedActionState['hasUnsavedChangesAlert'] = $action->hasUnsavedChangesAlert();
unset($mountedActionState);
if (! $this->mountedActionShouldOpenModal(mountedAction: $action)) {
if ($context['mountedFromUrl'] ?? false) {
// A modal-less action mounted from the URL has nothing to show the user, so
// running it here would let a crafted link trigger it with no interaction.
$this->unmountAction(cancelParentActions: false);
return null;
}
$result = $this->callMountedAction();
// The action can have stopped itself without unmounting, by halting, and it has no
// modal to stop in. If another action was mounted while it was running, it must remain
// on the stack until that action closes.
if ($this->getMountedAction() === $action) {
$this->unmountAction(cancelParentActions: false);
}
return $result;
}
$this->syncActionModals();
$this->resetErrorBag();
return null;
} finally {
$this->mountActionNestingLevel--;
}
}
/**
* Unmounts every action on top of the stack that has no modal to be seen in.
*/
protected function unmountActionsWithoutModals(): void
{
while (filled($this->mountedActions ?? [])) {
try {
$action = $this->getMountedAction();
} catch (ActionNotResolvableException $exception) {
$action = null;
}
if ($action && $this->mountedActionShouldOpenModal(mountedAction: $action)) {
break;
}
array_pop($this->mountedActions);
while (count($this->cachedMountedActions ?? []) > count($this->mountedActions)) {
array_pop($this->cachedMountedActions);
}
}
}
/**
* @param array<string, mixed> $arguments
*/
public function callMountedAction(array $arguments = []): mixed
{
$action = $this->getMountedAction();
if (! $action) {
return null;
}
$originalActionArguments = $action->getArguments();
$action->mergeArguments($arguments);
if ($action->isDisabled()) {
return null;
}
if (
$action->hasAuthorizationNotification() &&
(! $action->isAuthorized())
) {
return null;
}
if ($rateLimit = $action->getRateLimit()) {
try {
$this->rateLimit($rateLimit, method: json_encode(array_map(fn (array $action): array => Arr::except($action, ['data']), $this->mountedActions)));
} catch (TooManyRequestsException $exception) {
$action->sendRateLimitedNotification($exception);
return null;
}
}
$schema = $this->getMountedActionSchema(mountedAction: $action);
$originallyMountedActions = $this->mountedActions;
$result = null;
$hasFinalizedDatabaseTransaction = false;
try {
$action->beginDatabaseTransaction();
$schemaState = [];
if (($actionComponent = $action->getSchemaComponent()) instanceof ExposesStateToActionData) {
foreach ($actionComponent->getChildSchemas() as $actionComponentChildSchema) {
$schemaState = [
...$schemaState,
...$actionComponentChildSchema->getState(),
];
}
}
if ($this->mountedActionHasSchema(mountedAction: $action)) {
$action->callBeforeFormValidated();
$schema->getState(afterValidate: function (array $state) use ($action, $schemaState): void {
$action->callAfterFormValidated();
$action->data([
...$schemaState,
...$state,
]);
$action->callBefore();
});
} else {
$action->data($schemaState);
$action->callBefore();
}
$result = $action->call([
'form' => $schema,
'schema' => $schema,
]);
$result = $action->callAfter() ?? $result;
$this->afterActionCalled($action);
(match ($action->getStatus()) {
ActionStatus::Success => function () use ($action): void {
$action->sendSuccessNotification();
$action->dispatchSuccessRedirect();
},
ActionStatus::Failure => function () use ($action): void {
$action->sendFailureNotification();
$action->dispatchFailureRedirect();
},
})();
} catch (Halt $exception) {
$exception->shouldRollbackDatabaseTransaction() ?
$action->rollBackDatabaseTransaction() :
$action->commitDatabaseTransaction();
return null;
} catch (Cancel $exception) {
$exception->shouldRollbackDatabaseTransaction() ?
$action->rollBackDatabaseTransaction() :
$action->commitDatabaseTransaction();
$hasFinalizedDatabaseTransaction = true;
} catch (ValidationException $exception) {
$action->rollBackDatabaseTransaction();
if (! $this->mountedActionShouldOpenModal(mountedAction: $action)) {
$action->arguments($originalActionArguments);
$action->resetData();
$this->unmountAction();
}
throw $exception;
} catch (Throwable $exception) {
$action->rollBackDatabaseTransaction();
throw $exception;
}
if (! $hasFinalizedDatabaseTransaction) {
$action->commitDatabaseTransaction();
}
if (store($this)->has('redirect')) {
$this->unmountAction();
return $result;
}
$this->partiallyRenderActionParentSchema($action);
$action->arguments($originalActionArguments);
$action->resetData();
$onlyActionNamesAndContexts = fn (array $actions): array => collect($actions)
->map(fn (array $action): array => Arr::only($action, ['name', 'context']))
->all();
// If the action was replaced while it was being called,
// we don't want to unmount it.
if ($onlyActionNamesAndContexts($originallyMountedActions) !== $onlyActionNamesAndContexts($this->mountedActions)) {
$action->clearRecordAfter();
return null;
}
$this->unmountAction();
return $result;
}
public function forceRender(): void
{
app(PartialsComponentHook::class)->forceRender($this);
}
protected function partiallyRenderActionParentSchema(Action $action): void
{
$actionSchema = $action->getSchemaContainer() ?? $action->getSchemaComponent()?->getContainer();
$schemaToPartiallyRender = null;
while ($actionSchema !== null) {
if ($actionSchema->shouldPartiallyRender()) {
$schemaToPartiallyRender = $actionSchema;
}
$actionSchema = $actionSchema->getParentComponent()?->getContainer();
}
if (! $schemaToPartiallyRender) {
return;
}
app(PartialsComponentHook::class)->renderPartial($this, fn (): array => [
"schema.{$schemaToPartiallyRender->getKey()}" => $schemaToPartiallyRender->toHtml(...),
]);
}
protected function afterActionCalled(Action $action): void {}
/**
* @param array<string, mixed> $arguments
* @param array<string, mixed> $context
*/
public function replaceMountedAction(string $name, array $arguments = [], array $context = []): void
{
$this->mountedActions = [];
$this->cachedMountedActions = null;
$this->forgetCachedMountedActionSchemas();
$this->mountAction($name, $arguments, $context);
}
protected function forgetCachedMountedActionSchemas(int $fromNestingIndex = 0): void
{
foreach (array_keys($this->cachedSchemas) as $schemaName) {
if (! str_starts_with($schemaName, 'mountedActionSchema')) {
continue;
}
if (((int) substr($schemaName, strlen('mountedActionSchema'))) >= $fromNestingIndex) {
unset($this->cachedSchemas[$schemaName]);
}
}
}
public function cacheAction(Action $action): Action
{
$action->livewire($this);
return $this->cachedActions[$action->getName()] = $action;
}
/**
* @param array<string, Action> $actions
*/
protected function mergeCachedActions(array $actions): void
{
$this->cachedActions = [
...$this->cachedActions,
...$actions,
];
}
public function mountedActionShouldOpenModal(?Action $mountedAction = null): bool
{
return ($mountedAction ?? $this->getMountedAction())->shouldOpenModal(
checkForSchemaUsing: $this->mountedActionHasSchema(...),
);
}
public function mountedActionHasSchema(?Action $mountedAction = null): bool
{
return (bool) count($this->getMountedActionSchema(mountedAction: $mountedAction)?->getComponents() ?? []);
}
/**
* @deprecated Use `mountedActionHasSchema()` instead.
*/
public function mountedActionHasForm(?Action $mountedAction = null): bool
{
return $this->mountedActionHasSchema($mountedAction);
}
/**
* @return array<Action>
*/
public function getMountedActions(): array
{
if (blank($this->mountedActions ?? [])) {
return [];
}
if (array_key_exists(count($this->mountedActions) - 1, $this->cachedMountedActions ?? [])) {
return $this->cachedMountedActions;
}
return $this->cacheMountedActions($this->mountedActions);
}
public function cacheTraitActions(): void
{
foreach (class_uses_recursive($class = static::class) as $trait) {
$traitBasename = class_basename($trait);
if (
str($traitBasename)->endsWith('Actions') &&
method_exists($class, $method = "cache{$traitBasename}")
) {
$this->{$method}();
}
}
}
public function getMountedAction(?int $actionNestingIndex = null): ?Action
{
if (! count($this->mountedActions ?? [])) {
return null;
}
$actionNestingIndex ??= (count($this->mountedActions) - 1);
if (array_key_exists($actionNestingIndex, $this->cachedMountedActions ?? [])) {
return $this->cachedMountedActions[$actionNestingIndex];
}
$this->cacheMountedActions(
Arr::take($this->mountedActions, $actionNestingIndex + 1),
);
return Arr::last($this->cachedMountedActions);
}
/**
* @param array<string, mixed> $mountedActions
* @return array<Action>
*/
protected function cacheMountedActions(array $mountedActions): array
{
try {
return $this->cachedMountedActions = $this->resolveActions($mountedActions);
} catch (ActionNotResolvableException) {
return $this->cachedMountedActions = [];
}
}
/**
* @param array<array<string, mixed>> $actions
* @return array<Action>
*/
protected function resolveActions(array $actions, bool $isMounting = true): array
{
$resolvedActions = [];
foreach ($actions as $actionNestingIndex => $action) {
if (blank($action['name'] ?? null)) {
throw new ActionNotResolvableException('An action tried to resolve without a name.');
}
if (filled($action['context']['schemaComponent'] ?? null)) {
$resolvedAction = $this->resolveSchemaComponentAction($action, $resolvedActions);
} elseif ($this instanceof HasTable && filled($action['context']['table'] ?? null)) {
$resolvedAction = $this->resolveTableAction($action, $resolvedActions);
} else {
$resolvedAction = $this->resolveAction($action, $resolvedActions);
}
if (! $resolvedAction) {
continue;
}
if (filled($action['arguments'] ?? [])) {
$resolvedAction->mergeArguments($action['arguments']);
}
$resolvedAction->nestingIndex($actionNestingIndex);
$resolvedAction->boot();
$resolvedActions[] = $resolvedAction;
if ($isMounting) {
$this->cacheSchema(
"mountedActionSchema{$actionNestingIndex}",
$this->getMountedActionSchema($actionNestingIndex, $resolvedAction),
);
}
}
return $resolvedActions;
}
/**
* @param array<string, mixed> $action
* @param array<Action> $parentActions
*/
protected function resolveAction(array $action, array $parentActions): ?Action
{
if (count($parentActions)) {
$parentAction = Arr::last($parentActions);
$resolvedAction = $parentAction->getModalAction($action['name']) ?? throw new ActionNotResolvableException("Action [{$action['name']}] was not found for action [{$parentAction->getName()}].");
} elseif (array_key_exists($action['name'], $this->cachedActions)) {
$resolvedAction = $this->cachedActions[$action['name']];
} else {
if (
(! str($action['name'])->endsWith('Action')) &&
method_exists($this, "{$action['name']}Action")
) {
$methodName = "{$action['name']}Action";
} elseif (method_exists($this, $action['name'])) {
$methodName = $action['name'];
} else {
return null;
}
$returnTypeReflection = (new ReflectionMethod($this, $methodName))->getReturnType();
if (! $returnTypeReflection) {
return null;
}
$returnTypes = $returnTypeReflection instanceof ReflectionUnionType ? $returnTypeReflection->getTypes() : [$returnTypeReflection];
$hasActionReturnType = collect($returnTypes)
->filter(fn ($returnType) => $returnType instanceof ReflectionNamedType)
->contains(fn (ReflectionNamedType $returnType) => is_a($returnType->getName(), Action::class, allow_string: true));
if (! $hasActionReturnType) {
return null;
}
$resolvedAction = $this->{$methodName}();
if (! $resolvedAction instanceof Action) {
throw new ActionNotResolvableException('Actions must be an instance of ' . Action::class . ". The [{$methodName}] method on the Livewire component returned an instance of [" . get_class($resolvedAction) . '].');
}
$this->cacheAction($resolvedAction);
}
return $resolvedAction;
}
/**
* @param array<string, mixed> $action
* @param array<Action> $parentActions
*/
protected function resolveTableAction(array $action, array $parentActions): Action
{
if (! ($this instanceof HasTable)) {
throw new ActionNotResolvableException('Failed to resolve table action for Livewire component without the [' . HasTable::class . '] trait.');
}
if (count($parentActions)) {
$parentAction = Arr::last($parentActions);
return $parentAction->getModalAction($action['name']) ?? throw new ActionNotResolvableException("Action [{$action['name']}] was not found for action [{$parentAction->getName()}].");
}
if ($action['context']['bulk'] ?? false) {
$resolvedAction = $this->getTable()->getBulkAction($action['name']);
}
$resolvedAction ??= $this->getTable()->getAction($action['name']) ?? throw new ActionNotResolvableException("Action [{$action['name']}] not found on table.");
if (filled($action['context']['recordKey'] ?? null)) {
$record = $this->getTableRecord($action['context']['recordKey']);
if (! $record) {
throw new ActionNotResolvableException("Record [{$action['context']['recordKey']}] no longer exists.");
}
$resolvedAction->getRootGroup()?->record($record) ?? $resolvedAction->record($record);
}
return $resolvedAction;
}
/**
* @param array<string, mixed> $action
* @param array<Action> $parentActions
*/
protected function resolveSchemaComponentAction(array $action, array $parentActions): Action
{
if (! $this instanceof HasSchemas) {
throw new ActionNotResolvableException('Failed to resolve action schema for Livewire component without the [' . InteractsWithSchemas::class . '] trait.');
}
$key = $action['context']['schemaComponent'];
$schemaName = (string) str($key)->before('.');
$schema = $this->getSchema($schemaName);
if (! $schema) {
throw new ActionNotResolvableException("Schema [{$schemaName}] not found.");
}
$resolvedAction = $schema->getAction(
$action['name'],
str($key)->contains('.') ? (string) str($key)->after('.') : null,
);
if (! $resolvedAction) {
throw new ActionNotResolvableException("Action [{$action['name']}] not found in schema at [{$action['context']['schemaComponent']}].");
}
return $resolvedAction;
}
/**
* @param string | array<string | array<string, mixed>> $actions
*/
public function getAction(string | array $actions, bool $isMounting = true): ?Action
{
$actions = array_map(
fn (string | array $action): array => is_array($action) ? $action : ['name' => $action],
Arr::wrap($actions),
);
return Arr::last($this->resolveActions($actions, $isMounting));
}
public function getMountedActionSchemaName(): ?string
{
if (empty($this->mountedActions)) {
return null;
}
return 'mountedActionSchema' . array_key_last($this->mountedActions);
}
protected function getMountedActionSchema(?int $actionNestingIndex = null, ?Action $mountedAction = null): ?Schema
{
$actionNestingIndex ??= $mountedAction?->getNestingIndex() ?? array_key_last($this->mountedActions);
$mountedAction ??= $this->getMountedAction($actionNestingIndex);
if (! ($mountedAction instanceof Action)) {
return null;
}
if ((! $this->isCachingSchemas) && $this->hasCachedSchema("mountedActionSchema{$actionNestingIndex}")) {
return $this->getSchema("mountedActionSchema{$actionNestingIndex}");
}
return $mountedAction->getSchema(
$this->makeSchema()
->model(function () use ($mountedAction): Model | array | string | null {
$schemaComponent = $mountedAction->getSchemaComponent();
return $mountedAction->getRecord(withDefault: blank($schemaComponent)) ?? $mountedAction->getModel(withDefault: blank($schemaComponent)) ?? $schemaComponent?->getActionSchemaModel() ?? $this->getMountedActionSchemaModel();
})
->key("mountedActionSchema{$actionNestingIndex}")
->statePath("mountedActions.{$actionNestingIndex}.data")
->operation(
collect($this->mountedActions)
->take($actionNestingIndex + 1)
->pluck('name')
->implode('.'),
)
->rootHeadingLevel(3),
);
}
/**
* @deprecated Use `getMountedActionSchema()` instead.
*/
protected function getMountedActionForm(?int $actionNestingIndex = null, ?Action $mountedAction = null): ?Schema
{
return $this->getMountedActionSchema($actionNestingIndex, $mountedAction);
}
/**
* @return Model|class-string<Model>|null
*/
protected function getMountedActionSchemaModel(): Model | string | null
{
return null;
}
public function unmountAction(bool | string | null $cancelParentActions = null): void
{
try {
$action = $this->getMountedAction();
} catch (ActionNotResolvableException $exception) {
$action = null;
}
if (($cancelParentActions === false) || (! $action)) {
array_pop($this->mountedActions);
} elseif (
($cancelParentActions === true) ||
(($cancelParentActions === null) && $action->shouldCancelAllParentActions())
) {
$this->mountedActions = [];
} else {
$parentActionToCancelTo = is_string($cancelParentActions)
? $cancelParentActions
: $action->getParentActionToCancelTo();
while (true) {
$recentlyClosedParentAction = array_pop($this->mountedActions);
if (
blank($parentActionToCancelTo) ||
($recentlyClosedParentAction === null) ||
($recentlyClosedParentAction['name'] === $parentActionToCancelTo)
) {
break;
}
}
}
if ($this->mountActionNestingLevel === 0) {
// Closing a modal can expose an action that has no modal of its own, which
// would then be stuck on the stack with nothing to show.
$this->unmountActionsWithoutModals();
}
$this->syncActionModals();
while (count($this->cachedMountedActions ?? []) > count($this->mountedActions)) {
array_pop($this->cachedMountedActions);
}
// The schemas of the actions that have just closed, which are cached by nesting index: an
// action mounted at one of those indexes later in this request would otherwise be handed
// the schema of the action that used to be there, since `getMountedActionSchema()` reads
// the cache before it builds anything.
$this->forgetCachedMountedActionSchemas(fromNestingIndex: count($this->mountedActions));
if (! count($this->mountedActions)) {
$action?->clearRecordAfter();
// Setting these to `null` creates a bug where the properties are
// actually set to `'null'` strings and remain in the URL.
$this->defaultAction = [];
$this->defaultActionArguments = [];
$this->defaultActionContext = [];
return;
}
$this->resetErrorBag();
}
protected function syncActionModals(): void
{
$this->dispatch(
'sync-action-modals',
id: $this->getId(),
newActionNestingIndex: array_key_last($this->mountedActions),
shouldOverlayParentActions: $this->getMountedAction()?->shouldOverlayParentActions() ?? false,
);
}
public function getOriginallyMountedActionIndex(): ?int
{
return $this->originallyMountedActionIndex;
}
/**
* @param array<string, mixed> $arguments
*/
public function mergeMountedActionArguments(array $arguments): void
{
$this->mountedActions[array_key_last($this->mountedActions)]['arguments'] = array_merge(
$this->mountedActions[array_key_last($this->mountedActions)]['arguments'],
$arguments,
);
$this->getMountedAction()->mergeArguments($arguments);
}
public function getDefaultActionRecord(Action $action): ?Model
{
return null;
}
public function getDefaultActionRecordTitle(Action $action): ?string
{
return null;
}
/**
* @return ?class-string<Model>
*/
public function getDefaultActionModel(Action $action): ?string
{
return null;
}
public function getDefaultActionModelLabel(Action $action): ?string
{
return null;
}
public function getDefaultActionUrl(Action $action): ?string
{
return null;
}
public function getDefaultActionSuccessRedirectUrl(Action $action): ?string
{
return null;
}
public function getDefaultActionFailureRedirectUrl(Action $action): ?string
{
return null;
}
public function getDefaultActionRelationship(Action $action): ?Relation
{
return null;
}
public function getDefaultActionSchemaResolver(Action $action): ?Closure
{
return null;
}
public function getDefaultActionAuthorizationResponse(Action $action): ?Response
{
return null;
}
public function getDefaultActionIndividualRecordAuthorizationResponseResolver(Action $action): ?Closure
{
return null;
}
}

View file

@ -0,0 +1,389 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
use Filament\Actions\Action;
use Filament\Support\ArrayRecord;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use LogicException;
use function Filament\Support\get_model_label;
use function Filament\Support\locale_has_pluralization;
trait InteractsWithRecord
{
/**
* @var Model | class-string<Model> | array<string, mixed> | Closure | null
*/
protected Model | string | array | Closure | null $record = null;
protected ?Closure $resolveRecordUsing = null;
/**
* @var class-string<Model>|Closure|null
*/
protected string | Closure | null $model = null;
protected string | Closure | null $modelLabel = null;
protected string | Closure | null $pluralModelLabel = null;
protected string | Closure | null $recordTitle = null;
protected string | Closure | null $recordTitleAttribute = null;
/**
* @param Model | string | array<string, mixed> | Closure | null $record
*/
public function record(Model | string | array | Closure | null $record): static
{
$this->record = $record;
$this->clearVisibilityCache();
return $this;
}
public function resolveRecordUsing(?Closure $callback): static
{
$this->resolveRecordUsing = $callback;
return $this;
}
/**
* @param class-string<Model>|Closure|null $model
*/
public function model(string | Closure | null $model): static
{
$this->model = $model;
return $this;
}
public function modelLabel(string | Closure | null $label): static
{
$this->modelLabel = $label;
return $this;
}
public function pluralModelLabel(string | Closure | null $label): static
{
$this->pluralModelLabel = $label;
return $this;
}
public function recordTitle(string | Closure | null $title): static
{
$this->recordTitle = $title;
return $this;
}
public function recordTitleAttribute(string | Closure | null $attribute): static
{
$this->recordTitleAttribute = $attribute;
return $this;
}
/**
* @return Model | array<string, mixed> | null
*/
public function getRecord(bool $withDefault = true): Model | array | null
{
$record = $this->evaluate($this->record);
$isRecordKey = filled($record) && (! $record instanceof Model) && (! is_array($record));
if ($isRecordKey && (! $this->resolveRecordUsing)) {
throw new LogicException("Could not resolve record from key [{$record}] without a [resolveRecordUsing()] callback.");
}
if ($isRecordKey) {
$record = $this->evaluate($this->resolveRecordUsing, [
'key' => $record,
]);
}
if ($isRecordKey && $record && (! $this->record instanceof Closure)) {
$this->record = $record;
}
if ($record) {
return $this->ensureCorrectRecordType($record);
}
if ($record = $this->getGroup()?->getRecord($withDefault)) {
return $this->ensureCorrectRecordType($record);
}
if (($this instanceof Action) && $record = $this->getSchemaContainer()?->getRecord()) {
return $this->ensureCorrectRecordType($record);
}
if (($this instanceof Action) && $record = $this->getSchemaComponent()?->getRecord()) {
return $this->ensureCorrectRecordType($record);
}
return ($withDefault && ($this instanceof Action)) ? $this->ensureCorrectRecordType($this->getHasActionsLivewire()?->getDefaultActionRecord($this)) : null;
}
/**
* @param Model | array<string, mixed> | null $record
* @return Model | array<string, mixed> | null
*/
protected function ensureCorrectRecordType(Model | array | null $record): Model | array | null
{
if (
($record instanceof Model)
&& filled($customModel = $this->getCustomModel())
&& (! $record instanceof $customModel)
) {
return null;
}
return $record;
}
public function getRecordTitle(?Model $record = null): ?string
{
$record ??= $this->getRecord();
if (
($record instanceof Model)
&& filled($customModel = $this->getCustomModel())
&& (! $record instanceof $customModel)
) {
$record = null;
}
if ($record) {
if (filled($title = $this->getCustomRecordTitle($record))) {
return $title;
}
if (filled($title = $this->getTable()?->getRecordTitle($record))) {
return $title;
}
}
if ($this instanceof Action && filled($title = $this->getHasActionsLivewire()?->getDefaultActionRecordTitle($this))) {
return $title;
}
return $this->getModelLabel();
}
/**
* @param Model | array<string, mixed> $record
*/
public function resolveRecordKey(Model | array $record): ?string
{
if (is_array($record)) {
return strval($record[ArrayRecord::getKeyName()] ?? throw new LogicException('Record arrays must have a unique [' . ArrayRecord::getKeyName() . '] entry for identification.'));
}
$key = $record->getKey();
if (blank($key)) {
return null;
}
return strval($key);
}
public function getCustomRecordTitle(?Model $record = null): ?string
{
$record ??= $this->getRecord();
$title = $this->evaluate(
$this->recordTitle,
namedInjections: [
'record' => $record,
],
typedInjections: ($record instanceof Model) ? [
Model::class => $record,
$record::class => $record,
] : [],
);
if (filled($title)) {
return $title;
}
$titleAttribute = $this->getCustomRecordTitleAttribute();
if (blank($titleAttribute)) {
return null;
}
if (str_contains($titleAttribute, '->')) {
$titleAttribute = str_replace('->', '.', $titleAttribute);
}
return data_get($record, $titleAttribute);
}
public function getRecordTitleAttribute(): ?string
{
return $this->getCustomRecordTitleAttribute() ?? $this->getTable()?->getRecordTitleAttribute();
}
public function getCustomRecordTitleAttribute(): ?string
{
return $this->evaluate($this->recordTitleAttribute);
}
public function hasCustomRecordTitle(): bool
{
return filled($this->recordTitle);
}
public function hasCustomRecordTitleAttribute(): bool
{
return $this->recordTitleAttribute !== null;
}
public function hasRecord(): bool
{
return filled($this->record);
}
/**
* @return class-string<Model>|null
*/
public function getModel(bool $withDefault = true): ?string
{
$model = $this->getCustomModel();
if (filled($model)) {
return $model;
}
$model = $this->getTable()?->getModel();
if (filled($model)) {
return $model;
}
$record = $this->getRecord($withDefault);
if ($record instanceof Model) {
return $record::class;
}
if ($record = $this->getGroup()?->getModel($withDefault)) {
return $record;
}
if ($this instanceof Action && $model = $this->getSchemaContainer()?->getModel()) {
return $model;
}
if ($this instanceof Action && $model = $this->getSchemaComponent()?->getModel()) {
return $model;
}
return ($withDefault && ($this instanceof Action)) ? $this->getHasActionsLivewire()?->getDefaultActionModel($this) : null;
}
/**
* @return class-string<Model>|null
*/
public function getCustomModel(): ?string
{
return $this->evaluate($this->model);
}
public function getModelLabel(): ?string
{
$label = $this->getCustomModelLabel();
if (filled($label)) {
return $label;
}
$label = $this->getTable()?->getModelLabel();
if (filled($label)) {
return $label;
}
$model = $this->getModel();
$hasActionsLivewire = ($this instanceof Action) ? $this->getHasActionsLivewire() : null;
if (! $model) {
return $hasActionsLivewire?->getDefaultActionModelLabel($this);
}
if ($hasActionsLivewire && ($model === $hasActionsLivewire->getDefaultActionModel($this))) {
return $hasActionsLivewire->getDefaultActionModelLabel($this);
}
return get_model_label($model);
}
public function getTitleCaseModelLabel(): ?string
{
$modelLabel = $this->getModelLabel();
if (blank($modelLabel)) {
return null;
}
return Str::ucwords($modelLabel);
}
public function getCustomModelLabel(): ?string
{
return $this->evaluate($this->modelLabel);
}
public function getPluralModelLabel(): ?string
{
$label = $this->getCustomPluralModelLabel();
if (filled($label)) {
return $label;
}
$label = $this->getTable()?->getPluralModelLabel();
if (filled($label)) {
return $label;
}
$singularLabel = $this->getModelLabel();
if (blank($singularLabel)) {
return null;
}
if (locale_has_pluralization()) {
return Str::plural($singularLabel);
}
return $singularLabel;
}
public function getTitleCasePluralModelLabel(): ?string
{
$pluralModelLabel = $this->getPluralModelLabel();
if (blank($pluralModelLabel)) {
return null;
}
return Str::ucwords($pluralModelLabel);
}
public function getCustomPluralModelLabel(): ?string
{
return $this->evaluate($this->pluralModelLabel);
}
}

View file

@ -0,0 +1,203 @@
<?php
namespace Filament\Actions\Concerns;
use Closure;
use Filament\Support\Authorization\DenyResponse;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Support\Collection;
use Illuminate\Support\LazyCollection;
use LogicException;
trait InteractsWithSelectedRecords
{
protected bool | Closure $canAccessSelectedRecords = false;
protected int $totalSelectedRecordsCount = 0;
protected int $successfulSelectedRecordsCount = 0;
protected int $bulkAuthorizationFailureWithoutMessageCount = 0;
protected int $bulkProcessingFailureWithoutMessageCount = 0;
/**
* @var array<string>
*/
protected array $bulkAuthorizationFailureMessages = [];
/**
* @var array<string, array{message: string | Closure, count: int}>
*/
protected array $bulkProcessingFailureMessages = [];
public function accessSelectedRecords(bool | Closure $condition = true): static
{
$this->canAccessSelectedRecords = $condition;
return $this;
}
public function canAccessSelectedRecords(): bool
{
return (bool) $this->evaluate($this->canAccessSelectedRecords);
}
public function hasCanAccessSelectedRecords(): bool
{
return $this->canAccessSelectedRecords !== false;
}
public function getSelectedRecords(): EloquentCollection | Collection | LazyCollection
{
if (! $this->canAccessSelectedRecords()) {
throw new LogicException("The action [{$this->getName()}] is attempting to access the selected records from the table, but it is not using [accessSelectedRecords()], so they are not available.");
}
$records = $this->getLivewire()->getSelectedTableRecords($this->shouldFetchSelectedRecords(), $this->getSelectedRecordsChunkSize());
$this->totalSelectedRecordsCount = ($records instanceof LazyCollection)
? $this->getLivewire()->getSelectedTableRecordsQuery(shouldFetchSelectedRecords: false)->count()
: $records->count();
$this->successfulSelectedRecordsCount = $this->totalSelectedRecordsCount;
return $records;
}
public function getSelectedRecordsQuery(): Builder
{
if (! $this->canAccessSelectedRecords()) {
throw new LogicException("The action [{$this->getName()}] is attempting to access the selected records query from the table, but it is not using [accessSelectedRecords()], so they are not available.");
}
return $this->getLivewire()->getSelectedTableRecordsQuery($this->shouldFetchSelectedRecords(), $this->getSelectedRecordsChunkSize());
}
public function getIndividuallyAuthorizedSelectedRecords(): EloquentCollection | Collection | LazyCollection
{
if (! $this->shouldAuthorizeIndividualRecords()) {
return $this->getSelectedRecords();
}
$this->successfulSelectedRecordsCount = 0;
$authorizationResponses = [];
$failureCountsByAuthorizationResponse = [];
$failureCountWithoutAuthorizationResponse = 0;
try {
return $this->getSelectedRecords()->filter(function ($record) use (&$authorizationResponses, &$failureCountsByAuthorizationResponse, &$failureCountWithoutAuthorizationResponse) {
$response = $this->getIndividualRecordAuthorizationResponse($record);
if ($response->allowed()) {
return true;
}
if ($response instanceof DenyResponse) {
$responseKey = $response->getKey();
$authorizationResponses[$responseKey] ??= $response;
$failureCountsByAuthorizationResponse[$responseKey] ??= 0;
$failureCountsByAuthorizationResponse[$responseKey]++;
} elseif (filled($responseMessage = $response->message())) {
$responseKey = array_search($responseMessage, $authorizationResponses);
if ($responseKey === false) {
$authorizationResponses[] = $responseMessage;
$responseKey = array_key_last($authorizationResponses);
$failureCountsByAuthorizationResponse[$responseKey] = 0;
}
$failureCountsByAuthorizationResponse[$responseKey]++;
} else {
$failureCountWithoutAuthorizationResponse++;
}
$this->successfulSelectedRecordsCount--;
return false;
});
} finally {
$failureMessages = [];
if ($this->totalSelectedRecordsCount > $this->successfulSelectedRecordsCount) {
foreach ($authorizationResponses as $responseKey => $response) {
if ($response instanceof DenyResponse) {
$failureMessages[] = $response->message($failureCountsByAuthorizationResponse[$responseKey], $this->totalSelectedRecordsCount);
} else {
$failureMessages[] = $response;
}
}
}
$this->bulkAuthorizationFailureWithoutMessageCount = $failureCountWithoutAuthorizationResponse;
$this->bulkAuthorizationFailureMessages = $failureMessages;
}
}
public function reportBulkProcessingFailure(?string $key = null, string | Closure | null $message = null): void
{
if (filled($key)) {
$this->bulkProcessingFailureMessages[$key] = [
'message' => $message,
'count' => ($this->bulkProcessingFailureMessages[$key]['count'] ?? 0) + 1,
];
} else {
$this->bulkProcessingFailureWithoutMessageCount++;
}
$this->successfulSelectedRecordsCount--;
}
public function reportBulkProcessingSuccessfulRecordsCount(int $count): void
{
$this->bulkProcessingFailureWithoutMessageCount = $this->successfulSelectedRecordsCount - $count;
$this->successfulSelectedRecordsCount = $count;
}
public function reportCompleteBulkProcessingFailure(?string $key = null, string | Closure | null $message = null): void
{
if (filled($key)) {
$this->bulkProcessingFailureMessages[$key] = [
'message' => $message,
'count' => $this->getTotalSelectedRecordsCount(),
];
} else {
$this->bulkProcessingFailureWithoutMessageCount += $this->getTotalSelectedRecordsCount();
}
$this->successfulSelectedRecordsCount = 0;
}
/**
* @return array<string>
*/
public function getBulkProcessingFailureMessages(): array
{
return array_reduce(
$this->bulkProcessingFailureMessages,
function (array $carry, array $failure): array {
if (blank($failure['message'])) {
return $carry;
}
$carry[] = $this->evaluate($failure['message'], [
'count' => $failure['count'],
'failureCount' => $failure['count'],
'isAll' => $failure['count'] === $this->totalSelectedRecordsCount,
'total' => $this->totalSelectedRecordsCount,
'totalCount' => $this->totalSelectedRecordsCount,
]);
return $carry;
},
initial: [],
);
}
public function getTotalSelectedRecordsCount(): int
{
return $this->totalSelectedRecordsCount;
}
}