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,27 @@
<?php
namespace Filament\QueryBuilder\Constraints;
use Filament\QueryBuilder\Constraints\BooleanConstraint\Operators\IsTrueOperator;
use Filament\QueryBuilder\Constraints\Operators\IsFilledOperator;
use Filament\QueryBuilder\View\QueryBuilderIconAlias;
use Filament\Support\Facades\FilamentIcon;
use Filament\Support\Icons\Heroicon;
class BooleanConstraint extends Constraint
{
use Concerns\CanBeNullable;
protected function setUp(): void
{
parent::setUp();
$this->icon(FilamentIcon::resolve(QueryBuilderIconAlias::CONSTRAINTS_BOOLEAN) ?? Heroicon::CheckCircle);
$this->operators([
IsTrueOperator::class,
IsFilledOperator::make()
->visible(fn (): bool => $this->isNullable()),
]);
}
}

View file

@ -0,0 +1,45 @@
<?php
namespace Filament\QueryBuilder\Constraints\BooleanConstraint\Operators;
use Filament\QueryBuilder\Constraints\Operators\Operator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class IsTrueOperator extends Operator
{
public function getName(): string
{
return 'isTrue';
}
public function getLabel(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.boolean.is_true.label.inverse' :
'filament-query-builder::query-builder.operators.boolean.is_true.label.direct',
);
}
public function getSummary(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.boolean.is_true.summary.inverse' :
'filament-query-builder::query-builder.operators.boolean.is_true.summary.direct',
['attribute' => $this->getConstraint()->getAttributeLabel()],
);
}
/**
* @template TModel of Model
*
* @param Builder<TModel> $query
* @return Builder<TModel>
*/
public function apply(Builder $query, string $qualifiedColumn): Builder
{
return $query->where($qualifiedColumn, ! $this->isInverse());
}
}

View file

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

View file

@ -0,0 +1,37 @@
<?php
namespace Filament\QueryBuilder\Constraints\Concerns;
use Closure;
trait HasLabel
{
protected string | Closure | null $label = null;
protected bool $shouldTranslateLabel = false;
public function label(string | 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
{
$label = $this->evaluate($this->label) ?? (string) str($this->getName())
->before('.')
->kebab()
->replace(['-', '_'], ' ')
->ucfirst();
return $this->shouldTranslateLabel ? __($label) : $label;
}
}

View file

@ -0,0 +1,20 @@
<?php
namespace Filament\QueryBuilder\Constraints\Concerns;
trait HasName
{
protected string $name;
public function name(string $name): static
{
$this->name = $name;
return $this;
}
public function getName(): string
{
return $this->name;
}
}

View file

@ -0,0 +1,79 @@
<?php
namespace Filament\QueryBuilder\Constraints\Concerns;
use Filament\QueryBuilder\Constraints\Operators\Operator;
trait HasOperators
{
/** @var array<Operator> */
protected array $operators = [];
/**
* @param array<class-string<Operator> | Operator> $operators
*/
public function unshiftOperators(array $operators): static
{
foreach ($operators as $operator) {
if (is_string($operator)) {
$operator = $operator::make();
}
$operatorName = $operator->getName();
if (array_key_exists($operatorName, $this->operators)) {
unset($this->operators[$operatorName]);
}
$this->operators = [
$operatorName => $operator,
...$this->operators,
];
}
return $this;
}
/**
* @param array<class-string<Operator> | Operator> $operators
*/
public function operators(array $operators): static
{
$this->operators = [];
$this->pushOperators($operators);
return $this;
}
/**
* @param array<class-string<Operator> | Operator> $operators
*/
public function pushOperators(array $operators): static
{
foreach ($operators as $operator) {
if (is_string($operator)) {
$operator = $operator::make();
}
$this->operators[$operator->getName()] = $operator;
}
return $this;
}
/**
* @return array<Operator>
*/
public function getOperators(): array
{
return array_filter(
$this->operators,
fn (Operator $operator): bool => $operator->isVisible(),
);
}
public function getOperator(string $name): ?Operator
{
return $this->getOperators()[$name] ?? null;
}
}

View file

@ -0,0 +1,321 @@
<?php
namespace Filament\QueryBuilder\Constraints;
use Closure;
use Filament\Actions\Action;
use Filament\Forms\Components\Builder\Block;
use Filament\Forms\Components\Select;
use Filament\Forms\View\FormsIconAlias;
use Filament\QueryBuilder\Forms\Components\RuleBuilder;
use Filament\Schemas\Components\Actions;
use Filament\Schemas\Components\Flex;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Group;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Support\Components\Component;
use Filament\Support\Concerns\HasIcon;
use Filament\Support\Enums\Size;
use Filament\Support\Facades\FilamentIcon;
use Filament\Support\Icons\Heroicon;
use Illuminate\Database\Eloquent\Model;
use LogicException;
class Constraint extends Component
{
use Concerns\HasLabel;
use Concerns\HasName;
use Concerns\HasOperators;
use HasIcon;
public const OPERATOR_SELECT_NAME = 'operator';
protected string $evaluationIdentifier = 'constraint';
protected string | Closure | null $attribute = null;
protected string | Closure | null $attributeLabel = null;
protected string | Closure | null $relationship = null;
protected ?Closure $modifyRelationshipQueryUsing = null;
/**
* @var array<string, mixed> | null
*/
protected ?array $settings = null;
protected ?bool $isInverse = null;
/**
* @var ?class-string<Model>
*/
protected ?string $model = null;
final public function __construct(string $name)
{
$this->name($name);
}
public static function make(?string $name = null): static
{
$constraintClass = static::class;
$name ??= static::getDefaultName();
if (blank($name)) {
throw new LogicException("Constraint of class [$constraintClass] must have a unique name, passed to the [make()] method.");
}
$static = app($constraintClass, ['name' => $name]);
$static->configure();
return $static;
}
public static function getDefaultName(): ?string
{
return null;
}
public function getBuilderBlock(): Block
{
return Block::make($this->getName())
->label($this->getLabel())
->icon($this->getIcon())
->schema(function (): array {
$operatorSelectOptions = $this->getOperatorSelectOptions();
return [
Flex::make(function (Flex $component) use ($operatorSelectOptions): array {
/** @var RuleBuilder $builder */
$builder = $component->getContainer()->getParentComponent()->getContainer()->getParentComponent();
return [
Grid::make(['@md' => 2, '@xl' => 3, '!@sm' => 2, '!@md' => 3])
->schema([
Select::make(static::OPERATOR_SELECT_NAME)
->label($this->getLabel())
->options($operatorSelectOptions)
->default(array_key_first($operatorSelectOptions))
->live()
->afterStateUpdated(fn (Select $component, Get $get) => $component
->getContainer()
->getComponent('settings', withHidden: true)
->getChildSchema()
->fill($get('settings'))),
Group::make(function (Get $get): array {
$operator = $get(static::OPERATOR_SELECT_NAME);
if (blank($operator)) {
return [];
}
[$operatorName] = $this->parseOperatorString($operator);
$operator = $this->getOperator($operatorName);
if (! $operator) {
return [];
}
$operator->constraint($this);
try {
return $operator->getFormSchema();
} finally {
$operator->constraint(null);
}
})
->dense()
->statePath('settings')
->key('settings')
->columnSpan(['@xl' => 2, '!@md' => 2])
->columns(['@xl' => 2, '!@md' => 2])
->visible(fn (Group $component): bool => filled($component->getChildSchema()->getComponents())),
])
->dense(),
Actions::make([
Action::make($cloneActionName = $builder->getCloneActionName())
->label(__('filament-forms::components.builder.actions.clone.label'))
->icon(FilamentIcon::resolve(FormsIconAlias::COMPONENTS_BUILDER_ACTIONS_CLONE) ?? Heroicon::Square2Stack)
->color('gray')
->iconButton()
->size(Size::Small)
// Security: Cloning a rule duplicates a node in the tree, so it is blocked once the tree is at the `maxRules()` limit. Unlike the add button, this is a plain button whose disabled state is respected.
->disabled(fn (): bool => $builder->isAtRuleLimit())
->tooltip(fn (): ?string => $builder->getRuleLimitReachedTooltip())
->action($builder->getAction($cloneActionName)(['item' => (string) str($component->getContainer()->getStatePath(isAbsolute: false))->beforeLast('.data')])->getLivewireClickHandler()),
Action::make($deleteActionName = $builder->getDeleteActionName())
->label(__('filament-forms::components.builder.actions.delete.label'))
->icon(FilamentIcon::resolve(FormsIconAlias::COMPONENTS_BUILDER_ACTIONS_DELETE) ?? Heroicon::Trash)
->color('danger')
->iconButton()
->size(Size::Small)
->action($builder->getAction($deleteActionName)(['item' => (string) str($component->getContainer()->getStatePath(isAbsolute: false))->beforeLast('.data')])->getLivewireClickHandler()),
])->grow(false),
];
})
->gridContainer()
// Name each constraint row as a group so screen readers convey where a rule begins/ends and
// which attribute it filters (the per-block header is deliberately hidden, WCAG 1.3.1).
// `e()` is required: extra attributes are rendered without escaping, so the label would
// otherwise break out of the attribute.
->extraAttributes([
'role' => 'group',
'aria-label' => e(trim(strip_tags($this->getLabel()))),
]),
];
});
}
/**
* @return array<string, string>
*/
public function getOperatorSelectOptions(): array
{
$options = [];
foreach ($this->getOperators() as $operatorName => $operator) {
$operator->constraint($this);
$options[$operatorName] = $operator->inverse(false)->getLabel();
$options["{$operatorName}.inverse"] = $operator->inverse()->getLabel();
$operator->constraint(null);
$operator->inverse(null);
}
return $options;
}
/**
* @return array{string, bool}
*/
public function parseOperatorString(string $operator): array
{
if (str($operator)->endsWith('.inverse')) {
return [(string) str($operator)->beforeLast('.'), true];
}
return [$operator, false];
}
public function attribute(string | Closure | null $name): static
{
$this->attribute = $name;
return $this;
}
public function attributeLabel(string | Closure | null $label): static
{
$this->attributeLabel = $label;
return $this;
}
public function modifyRelationshipQueryUsing(?Closure $modifyQueryUsing): static
{
$this->modifyRelationshipQueryUsing = $modifyQueryUsing;
return $this;
}
public function relationship(string $name, string $titleAttribute, ?Closure $modifyQueryUsing = null): static
{
$this->attribute("{$name}.{$titleAttribute}");
$this->modifyRelationshipQueryUsing($modifyQueryUsing);
return $this;
}
/**
* @param ?class-string<Model> $model
*/
public function model(?string $model): static
{
$this->model = $model;
return $this;
}
/**
* @return ?class-string<Model>
*/
public function getModel(): ?string
{
return $this->model;
}
public function getAttribute(): string
{
return $this->evaluate($this->attribute) ?? $this->getName();
}
public function getAttributeLabel(): string
{
return $this->evaluate($this->attributeLabel) ?? $this->getLabel();
}
public function queriesRelationships(): bool
{
return str($this->getAttribute())->contains('.');
}
public function getRelationshipName(): string
{
return (string) str($this->getAttribute())->beforeLast('.');
}
public function getAttributeForQuery(): string
{
return (string) str($this->getAttribute())->afterLast('.');
}
public function getModifyRelationshipQueryUsing(): ?Closure
{
return $this->modifyRelationshipQueryUsing;
}
/**
* @param array<string, mixed> | null $settings
*/
public function settings(?array $settings): static
{
$this->settings = $settings;
return $this;
}
public function inverse(?bool $condition = true): static
{
$this->isInverse = $condition;
return $this;
}
/**
* @return array<string, mixed> | null
*/
public function getSettings(): ?array
{
return $this->settings;
}
public function isInverse(): ?bool
{
return $this->isInverse;
}
protected function resolveDefaultClosureDependencyForEvaluationByName(string $parameterName): array
{
return match ($parameterName) {
'isInverse' => [$this->isInverse()],
'settings' => [$this->getSettings()],
default => parent::resolveDefaultClosureDependencyForEvaluationByName($parameterName),
};
}
}

View file

@ -0,0 +1,50 @@
<?php
namespace Filament\QueryBuilder\Constraints;
use Closure;
use Filament\QueryBuilder\Constraints\DateConstraint\Operators\IsAfterOperator;
use Filament\QueryBuilder\Constraints\DateConstraint\Operators\IsBeforeOperator;
use Filament\QueryBuilder\Constraints\DateConstraint\Operators\IsDateOperator;
use Filament\QueryBuilder\Constraints\DateConstraint\Operators\IsMonthOperator;
use Filament\QueryBuilder\Constraints\DateConstraint\Operators\IsYearOperator;
use Filament\QueryBuilder\Constraints\Operators\IsFilledOperator;
use Filament\QueryBuilder\View\QueryBuilderIconAlias;
use Filament\Support\Facades\FilamentIcon;
use Filament\Support\Icons\Heroicon;
class DateConstraint extends Constraint
{
use Concerns\CanBeNullable;
protected bool | Closure $hasTime = false;
public function time(bool | Closure $condition = true): static
{
$this->hasTime = $condition;
return $this;
}
public function hasTime(): bool
{
return (bool) $this->evaluate($this->hasTime);
}
protected function setUp(): void
{
parent::setUp();
$this->icon(FilamentIcon::resolve(QueryBuilderIconAlias::CONSTRAINTS_DATE) ?? Heroicon::Calendar);
$this->operators([
IsAfterOperator::class,
IsBeforeOperator::class,
IsDateOperator::class,
IsMonthOperator::class,
IsYearOperator::class,
IsFilledOperator::make()
->visible(fn (): bool => $this->isNullable()),
]);
}
}

View file

@ -0,0 +1,36 @@
<?php
namespace Filament\QueryBuilder\Constraints\DateConstraint;
use Filament\Support\Contracts\HasLabel;
enum DateUnit: string implements HasLabel
{
case Second = 'second';
case Minute = 'minute';
case Hour = 'hour';
case Day = 'day';
case Week = 'week';
case Month = 'month';
case Quarter = 'quarter';
case Year = 'year';
public function getLabel(): string
{
return match ($this) {
self::Second => __('filament-query-builder::query-builder.operators.date.unit_labels.second'),
self::Minute => __('filament-query-builder::query-builder.operators.date.unit_labels.minute'),
self::Hour => __('filament-query-builder::query-builder.operators.date.unit_labels.hour'),
self::Day => __('filament-query-builder::query-builder.operators.date.unit_labels.day'),
self::Week => __('filament-query-builder::query-builder.operators.date.unit_labels.week'),
self::Month => __('filament-query-builder::query-builder.operators.date.unit_labels.month'),
self::Quarter => __('filament-query-builder::query-builder.operators.date.unit_labels.quarter'),
self::Year => __('filament-query-builder::query-builder.operators.date.unit_labels.year'),
};
}
public function isTimeUnit(): bool
{
return in_array($this, [self::Second, self::Minute, self::Hour], strict: true);
}
}

View file

@ -0,0 +1,305 @@
<?php
namespace Filament\QueryBuilder\Constraints\DateConstraint\Operators;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\QueryBuilder\Constraints\DateConstraint;
use Filament\QueryBuilder\Constraints\DateConstraint\DateUnit;
use Filament\QueryBuilder\Constraints\Operators\Operator;
use Filament\Schemas\Components\Component;
use Filament\Schemas\Components\FusedGroup;
use Filament\Schemas\Components\Utilities\Get;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
class IsAfterOperator extends Operator
{
public function getName(): string
{
return 'isAfter';
}
public function getLabel(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.date.is_after.label.inverse' :
'filament-query-builder::query-builder.operators.date.is_after.label.direct',
);
}
public function getSummary(): string
{
$settings = $this->getSettings();
$constraint = $this->getConstraint();
$hasTime = $constraint instanceof DateConstraint && $constraint->hasTime();
// Check if using relative mode
if (($settings['mode'] ?? null) === 'relative') {
$resolvedDate = $this->resolveRelativeDate($settings, $hasTime);
$parsedDate = Carbon::parse($resolvedDate);
$isTimeBasedFilter = $this->isTimeBasedFilter($settings);
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.date.is_after.summary.inverse' :
'filament-query-builder::query-builder.operators.date.is_after.summary.direct',
[
'attribute' => $constraint->getAttributeLabel(),
'date' => $hasTime && $isTimeBasedFilter ? $parsedDate->toFormattedDayDateString() . ' ' . $parsedDate->format('H:i:s') : $parsedDate->toFormattedDateString(),
],
);
}
$date = $this->getDateSetting('date');
$parsedDate = $date === null ? null : Carbon::parse($date);
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.date.is_after.summary.inverse' :
'filament-query-builder::query-builder.operators.date.is_after.summary.direct',
[
'attribute' => $constraint->getAttributeLabel(),
'date' => $parsedDate === null ? null : ($hasTime ? $parsedDate->toFormattedDayDateString() . ' ' . $parsedDate->format('H:i:s') : $parsedDate->toFormattedDateString()),
],
);
}
/**
* @return array<Component | Action | ActionGroup>
*/
public function getFormSchema(): array
{
$constraint = $this->getConstraint();
$hasTime = $constraint instanceof DateConstraint && $constraint->hasTime();
return [
Select::make('mode')
->label(__('filament-query-builder::query-builder.operators.date.form.mode.label'))
->selectablePlaceholder(false)
->live()
->options([
'absolute' => __('filament-query-builder::query-builder.operators.date.form.mode.options.absolute'),
'relative' => __('filament-query-builder::query-builder.operators.date.form.mode.options.relative'),
])
->default('absolute'),
DateTimePicker::make('date')
->label(__('filament-query-builder::query-builder.operators.date.form.date.label'))
->time($hasTime)
->hidden(fn (Get $get): bool => $get('mode') === 'relative')
->required(fn (Get $get): bool => $get('mode') !== 'relative'),
Select::make('preset')
->label(__('filament-query-builder::query-builder.operators.date.form.preset.label'))
->selectablePlaceholder(false)
->live()
->options($this->getPresetOptions($hasTime))
->default('past_month')
->hidden(fn (Get $get): bool => $get('mode') !== 'relative')
->required(fn (Get $get): bool => $get('mode') === 'relative'),
FusedGroup::make([
Select::make('tense')
->label(__('filament-query-builder::query-builder.operators.date.form.tense.label'))
->selectablePlaceholder(false)
->options([
'past' => __('filament-query-builder::query-builder.operators.date.form.tense.options.past'),
'future' => __('filament-query-builder::query-builder.operators.date.form.tense.options.future'),
])
->default('past')
->required(),
TextInput::make('relative_value')
->label(__('filament-query-builder::query-builder.operators.date.form.relative_value.label'))
->numeric()
->minValue(1)
->default(1)
->required(),
Select::make('relative_unit')
->label(__('filament-query-builder::query-builder.operators.date.form.relative_unit.label'))
->options(
collect(DateUnit::cases())
->reject(fn (DateUnit $unit): bool => (! $hasTime) && $unit->isTimeUnit())
->mapWithKeys(fn (DateUnit $unit): array => [$unit->value => $unit->getLabel()])
->all()
)
->default(DateUnit::Day->value)
->required(),
])
->columns(3)
->columnSpanFull()
->hidden(fn (Get $get): bool => $get('mode') !== 'relative' || $get('preset') !== 'custom'),
];
}
/**
* @return array<string, string>
*/
protected function getPresetOptions(bool $hasTime): array
{
$options = [
'past_decade' => __('filament-query-builder::query-builder.operators.date.presets.past_decade'),
'past_5_years' => __('filament-query-builder::query-builder.operators.date.presets.past_5_years'),
'past_2_years' => __('filament-query-builder::query-builder.operators.date.presets.past_2_years'),
'past_year' => __('filament-query-builder::query-builder.operators.date.presets.past_year'),
'past_6_months' => __('filament-query-builder::query-builder.operators.date.presets.past_6_months'),
'past_quarter' => __('filament-query-builder::query-builder.operators.date.presets.past_quarter'),
'past_month' => __('filament-query-builder::query-builder.operators.date.presets.past_month'),
'past_2_weeks' => __('filament-query-builder::query-builder.operators.date.presets.past_2_weeks'),
'past_week' => __('filament-query-builder::query-builder.operators.date.presets.past_week'),
];
if ($hasTime) {
$options['past_hour'] = __('filament-query-builder::query-builder.operators.date.presets.past_hour');
$options['past_minute'] = __('filament-query-builder::query-builder.operators.date.presets.past_minute');
}
$options += [
'this_decade' => __('filament-query-builder::query-builder.operators.date.presets.this_decade'),
'this_year' => __('filament-query-builder::query-builder.operators.date.presets.this_year'),
'this_quarter' => __('filament-query-builder::query-builder.operators.date.presets.this_quarter'),
'this_month' => __('filament-query-builder::query-builder.operators.date.presets.this_month'),
'today' => __('filament-query-builder::query-builder.operators.date.presets.today'),
];
if ($hasTime) {
$options['this_hour'] = __('filament-query-builder::query-builder.operators.date.presets.this_hour');
$options['this_minute'] = __('filament-query-builder::query-builder.operators.date.presets.this_minute');
$options['next_minute'] = __('filament-query-builder::query-builder.operators.date.presets.next_minute');
$options['next_hour'] = __('filament-query-builder::query-builder.operators.date.presets.next_hour');
}
$options += [
'next_week' => __('filament-query-builder::query-builder.operators.date.presets.next_week'),
'next_2_weeks' => __('filament-query-builder::query-builder.operators.date.presets.next_2_weeks'),
'next_month' => __('filament-query-builder::query-builder.operators.date.presets.next_month'),
'next_quarter' => __('filament-query-builder::query-builder.operators.date.presets.next_quarter'),
'next_6_months' => __('filament-query-builder::query-builder.operators.date.presets.next_6_months'),
'next_year' => __('filament-query-builder::query-builder.operators.date.presets.next_year'),
'next_2_years' => __('filament-query-builder::query-builder.operators.date.presets.next_2_years'),
'next_5_years' => __('filament-query-builder::query-builder.operators.date.presets.next_5_years'),
'next_decade' => __('filament-query-builder::query-builder.operators.date.presets.next_decade'),
'custom' => __('filament-query-builder::query-builder.operators.date.presets.custom'),
];
return $options;
}
public function apply(Builder $query, string $qualifiedColumn): Builder
{
$settings = $this->getSettings();
$constraint = $this->getConstraint();
$hasTime = $constraint instanceof DateConstraint && $constraint->hasTime();
// Check if using relative mode - only if mode is explicitly set to 'relative'
if (($settings['mode'] ?? null) === 'relative') {
$dateTime = $this->resolveRelativeDate($settings, $hasTime);
if ($hasTime && $this->isTimeBasedFilter($settings)) {
return $query->where($qualifiedColumn, $this->isInverse() ? '<' : '>=', $dateTime);
}
return $query->whereDate($qualifiedColumn, $this->isInverse() ? '<' : '>=', $dateTime);
}
$date = $this->getDateSetting('date');
// Security: skip applying the constraint when the tampered setting is not a scalar date.
if ($date === null) {
return $query;
}
if ($hasTime) {
return $query->where($qualifiedColumn, $this->isInverse() ? '<' : '>=', $date);
}
return $query->whereDate($qualifiedColumn, $this->isInverse() ? '<' : '>=', $date);
}
/**
* @param array<string, mixed> $settings
*/
protected function isTimeBasedFilter(array $settings): bool
{
$preset = $settings['preset'] ?? 'custom';
if (in_array($preset, ['this_minute', 'this_hour', 'past_minute', 'past_hour', 'next_minute', 'next_hour'], true)) {
return true;
}
if ($preset === 'custom') {
$unit = $settings['relative_unit'] ?? DateUnit::Day->value;
return in_array($unit, [DateUnit::Second->value, DateUnit::Minute->value, DateUnit::Hour->value], true);
}
return false;
}
/**
* @param array<string, mixed> $settings
*/
protected function resolveRelativeDate(array $settings, bool $hasTime = false): string
{
$preset = $settings['preset'] ?? 'custom';
return match ($preset) {
'past_decade' => Carbon::now()->subYears(10)->toDateString(),
'past_5_years' => Carbon::now()->subYears(5)->toDateString(),
'past_2_years' => Carbon::now()->subYears(2)->toDateString(),
'past_year' => Carbon::now()->subYear()->toDateString(),
'past_6_months' => Carbon::now()->subMonths(6)->toDateString(),
'past_quarter' => Carbon::now()->subQuarter()->toDateString(),
'past_month' => Carbon::now()->subMonth()->toDateString(),
'past_2_weeks' => Carbon::now()->subWeeks(2)->toDateString(),
'past_week' => Carbon::now()->subWeek()->toDateString(),
'past_hour' => Carbon::now()->subHour()->toDateTimeString(),
'past_minute' => Carbon::now()->subMinute()->toDateTimeString(),
'this_decade' => Carbon::now()->startOfDecade()->toDateString(),
'this_year' => Carbon::now()->startOfYear()->toDateString(),
'this_quarter' => Carbon::now()->startOfQuarter()->toDateString(),
'this_month' => Carbon::now()->startOfMonth()->toDateString(),
'today' => Carbon::today()->toDateString(),
'this_hour' => Carbon::now()->startOfHour()->toDateTimeString(),
'this_minute' => Carbon::now()->startOfMinute()->toDateTimeString(),
'next_minute' => Carbon::now()->addMinute()->toDateTimeString(),
'next_hour' => Carbon::now()->addHour()->toDateTimeString(),
'next_week' => Carbon::now()->addWeek()->toDateString(),
'next_2_weeks' => Carbon::now()->addWeeks(2)->toDateString(),
'next_month' => Carbon::now()->addMonth()->toDateString(),
'next_quarter' => Carbon::now()->addQuarter()->toDateString(),
'next_6_months' => Carbon::now()->addMonths(6)->toDateString(),
'next_year' => Carbon::now()->addYear()->toDateString(),
'next_2_years' => Carbon::now()->addYears(2)->toDateString(),
'next_5_years' => Carbon::now()->addYears(5)->toDateString(),
'next_decade' => Carbon::now()->addYears(10)->toDateString(),
'custom' => $this->resolveCustomRelativeDate($settings, $hasTime),
default => Carbon::today()->toDateString(),
};
}
/**
* @param array<string, mixed> $settings
*/
protected function resolveCustomRelativeDate(array $settings, bool $hasTime = false): string
{
$value = (int) ($settings['relative_value'] ?? 1);
$unit = $settings['relative_unit'] ?? DateUnit::Day->value;
$tense = $settings['tense'] ?? 'past';
$method = $tense === 'future' ? 'add' : 'sub';
return match ($unit) {
DateUnit::Second->value => Carbon::now()->{$method . 'Seconds'}($value)->toDateTimeString(),
DateUnit::Minute->value => Carbon::now()->{$method . 'Minutes'}($value)->toDateTimeString(),
DateUnit::Hour->value => Carbon::now()->{$method . 'Hours'}($value)->toDateTimeString(),
DateUnit::Day->value => Carbon::now()->{$method . 'Days'}($value)->toDateString(),
DateUnit::Week->value => Carbon::now()->{$method . 'Weeks'}($value)->toDateString(),
DateUnit::Month->value => Carbon::now()->{$method . 'Months'}($value)->toDateString(),
DateUnit::Quarter->value => Carbon::now()->{$method . 'Quarters'}($value)->toDateString(),
DateUnit::Year->value => Carbon::now()->{$method . 'Years'}($value)->toDateString(),
default => Carbon::today()->toDateString(),
};
}
}

View file

@ -0,0 +1,305 @@
<?php
namespace Filament\QueryBuilder\Constraints\DateConstraint\Operators;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\QueryBuilder\Constraints\DateConstraint;
use Filament\QueryBuilder\Constraints\DateConstraint\DateUnit;
use Filament\QueryBuilder\Constraints\Operators\Operator;
use Filament\Schemas\Components\Component;
use Filament\Schemas\Components\FusedGroup;
use Filament\Schemas\Components\Utilities\Get;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
class IsBeforeOperator extends Operator
{
public function getName(): string
{
return 'isBefore';
}
public function getLabel(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.date.is_before.label.inverse' :
'filament-query-builder::query-builder.operators.date.is_before.label.direct',
);
}
public function getSummary(): string
{
$settings = $this->getSettings();
$constraint = $this->getConstraint();
$hasTime = $constraint instanceof DateConstraint && $constraint->hasTime();
// Check if using relative mode
if (($settings['mode'] ?? null) === 'relative') {
$resolvedDate = $this->resolveRelativeDate($settings, $hasTime);
$parsedDate = Carbon::parse($resolvedDate);
$isTimeBasedFilter = $this->isTimeBasedFilter($settings);
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.date.is_before.summary.inverse' :
'filament-query-builder::query-builder.operators.date.is_before.summary.direct',
[
'attribute' => $constraint->getAttributeLabel(),
'date' => $hasTime && $isTimeBasedFilter ? $parsedDate->toFormattedDayDateString() . ' ' . $parsedDate->format('H:i:s') : $parsedDate->toFormattedDateString(),
],
);
}
$date = $this->getDateSetting('date');
$parsedDate = $date === null ? null : Carbon::parse($date);
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.date.is_before.summary.inverse' :
'filament-query-builder::query-builder.operators.date.is_before.summary.direct',
[
'attribute' => $constraint->getAttributeLabel(),
'date' => $parsedDate === null ? null : ($hasTime ? $parsedDate->toFormattedDayDateString() . ' ' . $parsedDate->format('H:i:s') : $parsedDate->toFormattedDateString()),
],
);
}
/**
* @return array<Component | Action | ActionGroup>
*/
public function getFormSchema(): array
{
$constraint = $this->getConstraint();
$hasTime = $constraint instanceof DateConstraint && $constraint->hasTime();
return [
Select::make('mode')
->label(__('filament-query-builder::query-builder.operators.date.form.mode.label'))
->selectablePlaceholder(false)
->live()
->options([
'absolute' => __('filament-query-builder::query-builder.operators.date.form.mode.options.absolute'),
'relative' => __('filament-query-builder::query-builder.operators.date.form.mode.options.relative'),
])
->default('absolute'),
DateTimePicker::make('date')
->label(__('filament-query-builder::query-builder.operators.date.form.date.label'))
->time($hasTime)
->hidden(fn (Get $get): bool => $get('mode') === 'relative')
->required(fn (Get $get): bool => $get('mode') !== 'relative'),
Select::make('preset')
->label(__('filament-query-builder::query-builder.operators.date.form.preset.label'))
->selectablePlaceholder(false)
->live()
->options($this->getPresetOptions($hasTime))
->default('past_month')
->hidden(fn (Get $get): bool => $get('mode') !== 'relative')
->required(fn (Get $get): bool => $get('mode') === 'relative'),
FusedGroup::make([
Select::make('tense')
->label(__('filament-query-builder::query-builder.operators.date.form.tense.label'))
->selectablePlaceholder(false)
->options([
'past' => __('filament-query-builder::query-builder.operators.date.form.tense.options.past'),
'future' => __('filament-query-builder::query-builder.operators.date.form.tense.options.future'),
])
->default('past')
->required(),
TextInput::make('relative_value')
->label(__('filament-query-builder::query-builder.operators.date.form.relative_value.label'))
->numeric()
->minValue(1)
->default(1)
->required(),
Select::make('relative_unit')
->label(__('filament-query-builder::query-builder.operators.date.form.relative_unit.label'))
->options(
collect(DateUnit::cases())
->reject(fn (DateUnit $unit): bool => (! $hasTime) && $unit->isTimeUnit())
->mapWithKeys(fn (DateUnit $unit): array => [$unit->value => $unit->getLabel()])
->all()
)
->default(DateUnit::Day->value)
->required(),
])
->columns(3)
->columnSpanFull()
->hidden(fn (Get $get): bool => $get('mode') !== 'relative' || $get('preset') !== 'custom'),
];
}
/**
* @return array<string, string>
*/
protected function getPresetOptions(bool $hasTime): array
{
$options = [
'past_decade' => __('filament-query-builder::query-builder.operators.date.presets.past_decade'),
'past_5_years' => __('filament-query-builder::query-builder.operators.date.presets.past_5_years'),
'past_2_years' => __('filament-query-builder::query-builder.operators.date.presets.past_2_years'),
'past_year' => __('filament-query-builder::query-builder.operators.date.presets.past_year'),
'past_6_months' => __('filament-query-builder::query-builder.operators.date.presets.past_6_months'),
'past_quarter' => __('filament-query-builder::query-builder.operators.date.presets.past_quarter'),
'past_month' => __('filament-query-builder::query-builder.operators.date.presets.past_month'),
'past_2_weeks' => __('filament-query-builder::query-builder.operators.date.presets.past_2_weeks'),
'past_week' => __('filament-query-builder::query-builder.operators.date.presets.past_week'),
];
if ($hasTime) {
$options['past_hour'] = __('filament-query-builder::query-builder.operators.date.presets.past_hour');
$options['past_minute'] = __('filament-query-builder::query-builder.operators.date.presets.past_minute');
}
$options += [
'this_decade' => __('filament-query-builder::query-builder.operators.date.presets.this_decade'),
'this_year' => __('filament-query-builder::query-builder.operators.date.presets.this_year'),
'this_quarter' => __('filament-query-builder::query-builder.operators.date.presets.this_quarter'),
'this_month' => __('filament-query-builder::query-builder.operators.date.presets.this_month'),
'today' => __('filament-query-builder::query-builder.operators.date.presets.today'),
];
if ($hasTime) {
$options['this_hour'] = __('filament-query-builder::query-builder.operators.date.presets.this_hour');
$options['this_minute'] = __('filament-query-builder::query-builder.operators.date.presets.this_minute');
$options['next_minute'] = __('filament-query-builder::query-builder.operators.date.presets.next_minute');
$options['next_hour'] = __('filament-query-builder::query-builder.operators.date.presets.next_hour');
}
$options += [
'next_week' => __('filament-query-builder::query-builder.operators.date.presets.next_week'),
'next_2_weeks' => __('filament-query-builder::query-builder.operators.date.presets.next_2_weeks'),
'next_month' => __('filament-query-builder::query-builder.operators.date.presets.next_month'),
'next_quarter' => __('filament-query-builder::query-builder.operators.date.presets.next_quarter'),
'next_6_months' => __('filament-query-builder::query-builder.operators.date.presets.next_6_months'),
'next_year' => __('filament-query-builder::query-builder.operators.date.presets.next_year'),
'next_2_years' => __('filament-query-builder::query-builder.operators.date.presets.next_2_years'),
'next_5_years' => __('filament-query-builder::query-builder.operators.date.presets.next_5_years'),
'next_decade' => __('filament-query-builder::query-builder.operators.date.presets.next_decade'),
'custom' => __('filament-query-builder::query-builder.operators.date.presets.custom'),
];
return $options;
}
public function apply(Builder $query, string $qualifiedColumn): Builder
{
$settings = $this->getSettings();
$constraint = $this->getConstraint();
$hasTime = $constraint instanceof DateConstraint && $constraint->hasTime();
// Check if using relative mode - only if mode is explicitly set to 'relative'
if (($settings['mode'] ?? null) === 'relative') {
$dateTime = $this->resolveRelativeDate($settings, $hasTime);
if ($hasTime && $this->isTimeBasedFilter($settings)) {
return $query->where($qualifiedColumn, $this->isInverse() ? '>' : '<=', $dateTime);
}
return $query->whereDate($qualifiedColumn, $this->isInverse() ? '>' : '<=', $dateTime);
}
$date = $this->getDateSetting('date');
// Security: skip applying the constraint when the tampered setting is not a scalar date.
if ($date === null) {
return $query;
}
if ($hasTime) {
return $query->where($qualifiedColumn, $this->isInverse() ? '>' : '<=', $date);
}
return $query->whereDate($qualifiedColumn, $this->isInverse() ? '>' : '<=', $date);
}
/**
* @param array<string, mixed> $settings
*/
protected function isTimeBasedFilter(array $settings): bool
{
$preset = $settings['preset'] ?? 'custom';
if (in_array($preset, ['this_minute', 'this_hour', 'past_minute', 'past_hour', 'next_minute', 'next_hour'], true)) {
return true;
}
if ($preset === 'custom') {
$unit = $settings['relative_unit'] ?? DateUnit::Day->value;
return in_array($unit, [DateUnit::Second->value, DateUnit::Minute->value, DateUnit::Hour->value], true);
}
return false;
}
/**
* @param array<string, mixed> $settings
*/
protected function resolveRelativeDate(array $settings, bool $hasTime = false): string
{
$preset = $settings['preset'] ?? 'custom';
return match ($preset) {
'past_decade' => Carbon::now()->subYears(10)->toDateString(),
'past_5_years' => Carbon::now()->subYears(5)->toDateString(),
'past_2_years' => Carbon::now()->subYears(2)->toDateString(),
'past_year' => Carbon::now()->subYear()->toDateString(),
'past_6_months' => Carbon::now()->subMonths(6)->toDateString(),
'past_quarter' => Carbon::now()->subQuarter()->toDateString(),
'past_month' => Carbon::now()->subMonth()->toDateString(),
'past_2_weeks' => Carbon::now()->subWeeks(2)->toDateString(),
'past_week' => Carbon::now()->subWeek()->toDateString(),
'past_hour' => Carbon::now()->subHour()->toDateTimeString(),
'past_minute' => Carbon::now()->subMinute()->toDateTimeString(),
'this_decade' => Carbon::now()->startOfDecade()->toDateString(),
'this_year' => Carbon::now()->startOfYear()->toDateString(),
'this_quarter' => Carbon::now()->startOfQuarter()->toDateString(),
'this_month' => Carbon::now()->startOfMonth()->toDateString(),
'today' => Carbon::today()->toDateString(),
'this_hour' => Carbon::now()->startOfHour()->toDateTimeString(),
'this_minute' => Carbon::now()->startOfMinute()->toDateTimeString(),
'next_minute' => Carbon::now()->addMinute()->toDateTimeString(),
'next_hour' => Carbon::now()->addHour()->toDateTimeString(),
'next_week' => Carbon::now()->addWeek()->toDateString(),
'next_2_weeks' => Carbon::now()->addWeeks(2)->toDateString(),
'next_month' => Carbon::now()->addMonth()->toDateString(),
'next_quarter' => Carbon::now()->addQuarter()->toDateString(),
'next_6_months' => Carbon::now()->addMonths(6)->toDateString(),
'next_year' => Carbon::now()->addYear()->toDateString(),
'next_2_years' => Carbon::now()->addYears(2)->toDateString(),
'next_5_years' => Carbon::now()->addYears(5)->toDateString(),
'next_decade' => Carbon::now()->addYears(10)->toDateString(),
'custom' => $this->resolveCustomRelativeDate($settings, $hasTime),
default => Carbon::today()->toDateString(),
};
}
/**
* @param array<string, mixed> $settings
*/
protected function resolveCustomRelativeDate(array $settings, bool $hasTime = false): string
{
$value = (int) ($settings['relative_value'] ?? 1);
$unit = $settings['relative_unit'] ?? DateUnit::Day->value;
$tense = $settings['tense'] ?? 'past';
$method = $tense === 'future' ? 'add' : 'sub';
return match ($unit) {
DateUnit::Second->value => Carbon::now()->{$method . 'Seconds'}($value)->toDateTimeString(),
DateUnit::Minute->value => Carbon::now()->{$method . 'Minutes'}($value)->toDateTimeString(),
DateUnit::Hour->value => Carbon::now()->{$method . 'Hours'}($value)->toDateTimeString(),
DateUnit::Day->value => Carbon::now()->{$method . 'Days'}($value)->toDateString(),
DateUnit::Week->value => Carbon::now()->{$method . 'Weeks'}($value)->toDateString(),
DateUnit::Month->value => Carbon::now()->{$method . 'Months'}($value)->toDateString(),
DateUnit::Quarter->value => Carbon::now()->{$method . 'Quarters'}($value)->toDateString(),
DateUnit::Year->value => Carbon::now()->{$method . 'Years'}($value)->toDateString(),
default => Carbon::today()->toDateString(),
};
}
}

View file

@ -0,0 +1,65 @@
<?php
namespace Filament\QueryBuilder\Constraints\DateConstraint\Operators;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\DatePicker;
use Filament\QueryBuilder\Constraints\Operators\Operator;
use Filament\Schemas\Components\Component;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
class IsDateOperator extends Operator
{
public function getName(): string
{
return 'isDate';
}
public function getLabel(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.date.is_date.label.inverse' :
'filament-query-builder::query-builder.operators.date.is_date.label.direct',
);
}
public function getSummary(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.date.is_date.summary.inverse' :
'filament-query-builder::query-builder.operators.date.is_date.summary.direct',
[
'attribute' => $this->getConstraint()->getAttributeLabel(),
'date' => ($date = $this->getDateSetting('date')) === null ? null : Carbon::parse($date)->toFormattedDateString(),
],
);
}
/**
* @return array<Component | Action | ActionGroup>
*/
public function getFormSchema(): array
{
return [
DatePicker::make('date')
->label(__('filament-query-builder::query-builder.operators.date.form.date.label'))
->required(),
];
}
public function apply(Builder $query, string $qualifiedColumn): Builder
{
$date = $this->getDateSetting('date');
// Security: skip applying the constraint when the tampered setting is not a scalar date.
if ($date === null) {
return $query;
}
return $query->whereDate($qualifiedColumn, $this->isInverse() ? '!=' : '=', $date);
}
}

View file

@ -0,0 +1,98 @@
<?php
namespace Filament\QueryBuilder\Constraints\DateConstraint\Operators;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\Select;
use Filament\QueryBuilder\Constraints\Operators\Operator;
use Filament\Schemas\Components\Component;
use Illuminate\Database\Eloquent\Builder;
class IsMonthOperator extends Operator
{
public function getName(): string
{
return 'isMonth';
}
public function getLabel(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.date.is_month.label.inverse' :
'filament-query-builder::query-builder.operators.date.is_month.label.direct',
);
}
public function getSummary(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.date.is_month.summary.inverse' :
'filament-query-builder::query-builder.operators.date.is_month.summary.direct',
[
'attribute' => $this->getConstraint()->getAttributeLabel(),
'month' => $this->getMonths()[$this->getMonthSetting()] ?? null,
],
);
}
/**
* @return array<Component | Action | ActionGroup>
*/
public function getFormSchema(): array
{
return [
Select::make('month')
->label(__('filament-query-builder::query-builder.operators.date.form.month.label'))
->options($this->getMonths())
->required(),
];
}
/**
* @return array<string>
*/
protected function getMonths(): array
{
return collect(range(1, 12))
->mapWithKeys(fn (int $month): array => [
$month => now()->setMonth($month)->setDay(1)->getTranslatedMonthName(),
])
->all();
}
public function apply(Builder $query, string $qualifiedColumn): Builder
{
$month = $this->getMonthSetting();
// Security: skip applying the constraint when the tampered setting is not a valid month.
if ($month === null) {
return $query;
}
return $query->whereMonth($qualifiedColumn, $this->isInverse() ? '!=' : '=', $month);
}
protected function getMonthSetting(): ?int
{
$month = $this->getSettings()['month'] ?? null;
// Security: settings arrive from the request payload and can be tampered with, so a
// non-scalar value (e.g. an array) must not reach `whereMonth()` or the `getMonths()`
// offset lookup where it would throw. Fail closed by returning `null` for any value
// that is not a real calendar month.
if (! is_scalar($month)) {
return null;
}
$month = (int) $month;
if (($month < 1) || ($month > 12)) {
return null;
}
return $month;
}
}

View file

@ -0,0 +1,79 @@
<?php
namespace Filament\QueryBuilder\Constraints\DateConstraint\Operators;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\TextInput;
use Filament\QueryBuilder\Constraints\Operators\Operator;
use Filament\Schemas\Components\Component;
use Illuminate\Database\Eloquent\Builder;
class IsYearOperator extends Operator
{
public function getName(): string
{
return 'isYear';
}
public function getLabel(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.date.is_year.label.inverse' :
'filament-query-builder::query-builder.operators.date.is_year.label.direct',
);
}
public function getSummary(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.date.is_year.summary.inverse' :
'filament-query-builder::query-builder.operators.date.is_year.summary.direct',
[
'attribute' => $this->getConstraint()->getAttributeLabel(),
'year' => $this->getYearSetting(),
],
);
}
/**
* @return array<Component | Action | ActionGroup>
*/
public function getFormSchema(): array
{
return [
TextInput::make('year')
->label(__('filament-query-builder::query-builder.operators.date.form.year.label'))
->integer()
->required(),
];
}
public function apply(Builder $query, string $qualifiedColumn): Builder
{
$year = $this->getYearSetting();
// Security: skip applying the constraint when the tampered setting is not a valid year.
if ($year === null) {
return $query;
}
return $query->whereYear($qualifiedColumn, $this->isInverse() ? '!=' : '=', $year);
}
protected function getYearSetting(): ?int
{
$year = $this->getSettings()['year'] ?? null;
// Security: settings arrive from the request payload and can be tampered with, so a
// non-numeric value (e.g. an array) must not reach `whereYear()` where it would throw.
// Fail closed by returning `null` instead.
if (! is_numeric($year)) {
return null;
}
return (int) $year;
}
}

View file

@ -0,0 +1,63 @@
<?php
namespace Filament\QueryBuilder\Constraints;
use Closure;
use Filament\QueryBuilder\Constraints\NumberConstraint\Operators\EqualsOperator;
use Filament\QueryBuilder\Constraints\NumberConstraint\Operators\IsMaxOperator;
use Filament\QueryBuilder\Constraints\NumberConstraint\Operators\IsMinOperator;
use Filament\QueryBuilder\Constraints\Operators\IsFilledOperator;
use Filament\QueryBuilder\View\QueryBuilderIconAlias;
use Filament\Support\Facades\FilamentIcon;
use Filament\Support\Icons\Heroicon;
class NumberConstraint extends Constraint
{
use Concerns\CanBeNullable;
/**
* @var array<string, string>
*/
protected array $existingAggregateAliases = [];
protected bool | Closure $isInteger = false;
protected function setUp(): void
{
parent::setUp();
$this->icon(FilamentIcon::resolve(QueryBuilderIconAlias::CONSTRAINTS_NUMBER) ?? Heroicon::Variable);
$this->operators([
IsMinOperator::class,
IsMaxOperator::class,
EqualsOperator::class,
IsFilledOperator::make()
->visible(fn (): bool => $this->isNullable()),
]);
}
public function integer(bool | Closure $condition = true): static
{
$this->isInteger = $condition;
return $this;
}
public function isInteger(): bool
{
return (bool) $this->evaluate($this->isInteger);
}
public function reportAggregateAlias(string $alias): static
{
$this->existingAggregateAliases[$alias] = $alias;
return $this;
}
public function isExistingAggregateAlias(string $alias): bool
{
return array_key_exists($alias, $this->existingAggregateAliases);
}
}

View file

@ -0,0 +1,155 @@
<?php
namespace Filament\QueryBuilder\Constraints\NumberConstraint\Operators\Concerns;
use Filament\Forms\Components\Select;
use Filament\QueryBuilder\Constraints\NumberConstraint;
use Illuminate\Database\Connection;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasOneOrMany;
use Illuminate\Database\Eloquent\Relations\Relation;
use LogicException;
trait CanAggregateRelationships
{
public static function getAggregateSelectName(): string
{
return 'aggregate';
}
public static function getAggregateAverageKey(): string
{
return 'avg';
}
public static function getAggregateMaxKey(): string
{
return 'max';
}
public static function getAggregateMinKey(): string
{
return 'min';
}
public static function getAggregateSumKey(): string
{
return 'sum';
}
public function queriesRelationshipsUsingSubSelect(): bool
{
return parent::queriesRelationshipsUsingSubSelect() && blank($this->getSettings()[static::getAggregateSelectName()]);
}
protected function getNumericCastType(Builder $query): string
{
/** @var Connection $databaseConnection */
$databaseConnection = $query->getConnection();
$driver = $databaseConnection->getDriverName();
return match ($driver) {
'sqlite' => 'real',
'pgsql' => 'numeric',
default => 'decimal(10,2)',
};
}
protected function applyAggregateComparison(Builder $query, string $operator, float $value): Builder
{
$relationshipName = $this->getConstraint()->getRelationshipName();
$attributeForQuery = $this->getConstraint()->getAttributeForQuery();
$aggregate = $this->getAggregate();
$modifyRelationshipQueryUsing = $this->getConstraint()->getModifyRelationshipQueryUsing();
/** @var Relation $relationship */
$relationship = Relation::noConstraints(
static fn (): Relation => $query->getModel()->{$relationshipName}(),
);
$relatedModel = $relationship->getModel();
$castType = $this->getNumericCastType($query);
if (! ($relationship instanceof BelongsToMany) && ! ($relationship instanceof HasOneOrMany)) {
throw new LogicException('Relationship type [' . get_class($relationship) . '] is not supported for aggregate queries.');
}
$subQuery = $relationship->getRelationExistenceQuery(
$relatedModel->newQueryWithoutRelationships(),
$query,
[],
)->mergeConstraintsFrom($relationship->getQuery());
$attributeForQuery = $subQuery->qualifyColumn($attributeForQuery);
$attributeForQuery = $subQuery->getQuery()->getGrammar()->wrap($attributeForQuery);
$subQuery->selectRaw("cast({$aggregate}({$attributeForQuery}) as {$castType})");
if ($modifyRelationshipQueryUsing) {
$subQuery = $this->evaluate($modifyRelationshipQueryUsing, ['query' => $subQuery]) ?? $subQuery;
}
return $query->whereRaw("({$subQuery->toSql()}) {$operator} ?", [...$subQuery->getBindings(), $value]);
}
protected function getAggregateSelect(): Select
{
return Select::make(static::getAggregateSelectName())
->label(__('filament-query-builder::query-builder.operators.number.form.aggregate.label'))
->options([
static::getAggregateSumKey() => __('filament-query-builder::query-builder.operators.number.aggregates.sum.label'),
static::getAggregateAverageKey() => __('filament-query-builder::query-builder.operators.number.aggregates.average.label'),
static::getAggregateMaxKey() => __('filament-query-builder::query-builder.operators.number.aggregates.max.label'),
static::getAggregateMinKey() => __('filament-query-builder::query-builder.operators.number.aggregates.min.label'),
])
->visible($this->getConstraint()->queriesRelationships());
}
protected function getAggregate(): ?string
{
$aggregate = $this->getSettings()[static::getAggregateSelectName()] ?? null;
if ($aggregate === null) {
return null;
}
// Security: a tampered request can set the aggregate to a non-scalar (e.g. an array),
// which would throw a `TypeError` at the `array_key_exists()` offset check below. Fail
// closed by treating anything that is not a recognised option as no aggregate.
if (! is_scalar($aggregate)) {
return null;
}
if (! array_key_exists($aggregate, $this->getAggregateSelect()->getOptions())) {
return null;
}
return (string) $aggregate;
}
protected function getAttributeLabel(): string
{
$attributeLabel = $this->getConstraint()->getAttributeLabel();
return __(match ($this->getAggregate()) {
static::getAggregateAverageKey() => 'filament-query-builder::query-builder.operators.number.aggregates.average.summary',
static::getAggregateMaxKey() => 'filament-query-builder::query-builder.operators.number.aggregates.max.summary',
static::getAggregateMinKey() => 'filament-query-builder::query-builder.operators.number.aggregates.min.summary',
static::getAggregateSumKey() => 'filament-query-builder::query-builder.operators.number.aggregates.sum.summary',
default => $attributeLabel,
}, ['attribute' => $attributeLabel]);
}
public function getConstraint(): ?NumberConstraint
{
$constraint = parent::getConstraint();
if (! ($constraint instanceof NumberConstraint)) {
throw new LogicException('Constraint must be an instance of [' . NumberConstraint::class . '].');
}
return $constraint;
}
}

View file

@ -0,0 +1,74 @@
<?php
namespace Filament\QueryBuilder\Constraints\NumberConstraint\Operators;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\TextInput;
use Filament\QueryBuilder\Constraints\Operators\Operator;
use Filament\Schemas\Components\Component;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Number;
class EqualsOperator extends Operator
{
use Concerns\CanAggregateRelationships;
public function getName(): string
{
return 'equals';
}
public function getLabel(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.number.equals.label.inverse' :
'filament-query-builder::query-builder.operators.number.equals.label.direct',
);
}
public function getSummary(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.number.equals.summary.inverse' :
'filament-query-builder::query-builder.operators.number.equals.summary.direct',
[
'attribute' => $this->getAttributeLabel(),
'number' => ($number = $this->getNumericSetting('number')) === null ? null : Number::format($number),
],
);
}
/**
* @return array<Component | Action | ActionGroup>
*/
public function getFormSchema(): array
{
return [
TextInput::make('number')
->label(__('filament-query-builder::query-builder.operators.number.form.number.label'))
->numeric()
->integer($this->getConstraint()->isInteger())
->required(),
$this->getAggregateSelect(),
];
}
public function apply(Builder $query, string $qualifiedColumn): Builder
{
$number = $this->getNumericSetting('number');
// Security: skip applying the constraint when the tampered setting is not numeric.
if ($number === null) {
return $query;
}
if (filled($this->getAggregate())) {
return $this->applyAggregateComparison($query, $this->isInverse() ? '!=' : '=', $number);
}
return $query->where($qualifiedColumn, $this->isInverse() ? '!=' : '=', $number);
}
}

View file

@ -0,0 +1,74 @@
<?php
namespace Filament\QueryBuilder\Constraints\NumberConstraint\Operators;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\TextInput;
use Filament\QueryBuilder\Constraints\Operators\Operator;
use Filament\Schemas\Components\Component;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Number;
class IsMaxOperator extends Operator
{
use Concerns\CanAggregateRelationships;
public function getName(): string
{
return 'isMax';
}
public function getLabel(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.number.is_max.label.inverse' :
'filament-query-builder::query-builder.operators.number.is_max.label.direct',
);
}
public function getSummary(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.number.is_max.summary.inverse' :
'filament-query-builder::query-builder.operators.number.is_max.summary.direct',
[
'attribute' => $this->getAttributeLabel(),
'number' => ($number = $this->getNumericSetting('number')) === null ? null : Number::format($number),
],
);
}
/**
* @return array<Component | Action | ActionGroup>
*/
public function getFormSchema(): array
{
return [
TextInput::make('number')
->label(__('filament-query-builder::query-builder.operators.number.form.number.label'))
->numeric()
->integer($this->getConstraint()->isInteger())
->required(),
$this->getAggregateSelect(),
];
}
public function apply(Builder $query, string $qualifiedColumn): Builder
{
$number = $this->getNumericSetting('number');
// Security: skip applying the constraint when the tampered setting is not numeric.
if ($number === null) {
return $query;
}
if (filled($this->getAggregate())) {
return $this->applyAggregateComparison($query, $this->isInverse() ? '>' : '<=', $number);
}
return $query->where($qualifiedColumn, $this->isInverse() ? '>' : '<=', $number);
}
}

View file

@ -0,0 +1,74 @@
<?php
namespace Filament\QueryBuilder\Constraints\NumberConstraint\Operators;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\TextInput;
use Filament\QueryBuilder\Constraints\Operators\Operator;
use Filament\Schemas\Components\Component;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Number;
class IsMinOperator extends Operator
{
use Concerns\CanAggregateRelationships;
public function getName(): string
{
return 'isMin';
}
public function getLabel(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.number.is_min.label.inverse' :
'filament-query-builder::query-builder.operators.number.is_min.label.direct',
);
}
public function getSummary(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.number.is_min.summary.inverse' :
'filament-query-builder::query-builder.operators.number.is_min.summary.direct',
[
'attribute' => $this->getAttributeLabel(),
'number' => ($number = $this->getNumericSetting('number')) === null ? null : Number::format($number),
],
);
}
/**
* @return array<Component | Action | ActionGroup>
*/
public function getFormSchema(): array
{
return [
TextInput::make('number')
->label(__('filament-query-builder::query-builder.operators.number.form.number.label'))
->numeric()
->integer($this->getConstraint()->isInteger())
->required(),
$this->getAggregateSelect(),
];
}
public function apply(Builder $query, string $qualifiedColumn): Builder
{
$number = $this->getNumericSetting('number');
// Security: skip applying the constraint when the tampered setting is not numeric.
if ($number === null) {
return $query;
}
if (filled($this->getAggregate())) {
return $this->applyAggregateComparison($query, $this->isInverse() ? '<' : '>=', $number);
}
return $query->where($qualifiedColumn, $this->isInverse() ? '<' : '>=', $number);
}
}

View file

@ -0,0 +1,40 @@
<?php
namespace Filament\QueryBuilder\Constraints\Operators\Concerns;
use Closure;
trait CanBeHidden
{
protected bool | Closure $isHidden = false;
protected bool | Closure $isVisible = true;
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->evaluate($this->isHidden)) {
return true;
}
return ! $this->evaluate($this->isVisible);
}
public function isVisible(): bool
{
return ! $this->isHidden();
}
}

View file

@ -0,0 +1,59 @@
<?php
namespace Filament\QueryBuilder\Constraints\Operators;
use Illuminate\Database\Connection;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\Expression;
use Illuminate\Support\Str;
class IsFilledOperator extends Operator
{
public function getName(): string
{
return 'isFilled';
}
public function getLabel(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.is_filled.label.inverse' :
'filament-query-builder::query-builder.operators.is_filled.label.direct',
);
}
public function getSummary(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.is_filled.summary.inverse' :
'filament-query-builder::query-builder.operators.is_filled.summary.direct',
['attribute' => $this->getConstraint()->getAttributeLabel()],
);
}
public function apply(Builder $query, string $qualifiedColumn): Builder
{
$qualifiedStringColumn = $qualifiedColumn;
/** @var Connection $databaseConnection */
$databaseConnection = $query->getConnection();
$isPostgres = $databaseConnection->getDriverName() === 'pgsql';
if ((Str::lower($qualifiedColumn) !== $qualifiedColumn) && $isPostgres) {
$qualifiedColumn = (string) str($qualifiedColumn)->wrap('"');
}
if ($isPostgres) {
$qualifiedStringColumn = new Expression("{$qualifiedColumn}::text");
}
return $query->where(
fn (Builder $query) => $query
->{$this->isInverse() ? 'whereNull' : 'whereNotNull'}($qualifiedColumn)
->{$this->isInverse() ? 'orWhere' : 'whereNot'}($qualifiedStringColumn, ''),
);
}
}

View file

@ -0,0 +1,291 @@
<?php
namespace Filament\QueryBuilder\Constraints\Operators;
use Closure;
use Filament\QueryBuilder\Constraints\Constraint;
use Filament\QueryBuilder\Constraints\Operators\Concerns\CanBeHidden;
use Filament\Support\Components\Component;
use Illuminate\Database\Eloquent\Builder;
class Operator extends Component
{
use CanBeHidden;
protected string $evaluationIdentifier = 'operator';
protected ?Constraint $constraint = null;
/**
* @var array<string, mixed> | null
*/
protected ?array $settings = null;
protected ?bool $isInverse = null;
protected ?string $name = null;
protected string | Closure | null $label = null;
protected string | Closure | null $summary = null;
protected ?Closure $modifyQueryUsing = null;
protected ?Closure $modifyBaseQueryUsing = null;
final public function __construct(?string $name = null)
{
$this->name($name);
}
public static function make(?string $name = null): static
{
$static = app(static::class, ['name' => $name]);
$static->configure();
return $static;
}
public function name(?string $name): static
{
$this->name = $name;
return $this;
}
public function label(string | Closure | null $label): static
{
$this->label = $label;
return $this;
}
public function summary(string | Closure | null $summary): static
{
$this->summary = $summary;
return $this;
}
public function query(?Closure $callback): static
{
$this->modifyQueryUsing($callback);
return $this;
}
public function baseQuery(?Closure $callback): static
{
$this->modifyBaseQueryUsing($callback);
return $this;
}
public function modifyQueryUsing(?Closure $callback): static
{
$this->modifyQueryUsing = $callback;
return $this;
}
public function modifyBaseQueryUsing(?Closure $callback): static
{
$this->modifyBaseQueryUsing = $callback;
return $this;
}
public function getName(): string
{
return $this->name;
}
public function getLabel(): string
{
return $this->evaluate($this->label) ?? (string) str($this->getName())
->before('.')
->kebab()
->replace(['-', '_'], ' ')
->ucfirst();
}
public function getSummary(): string
{
return $this->evaluate($this->summary);
}
public function apply(Builder $query, string $qualifiedColumn): Builder
{
return $query;
}
public function applyToBaseQuery(Builder $query): Builder
{
if ($this->hasBaseQueryModificationCallback()) {
return $this->evaluate($this->modifyBaseQueryUsing, [
'query' => $query,
]) ?? $query;
}
if ($this->queriesRelationshipsUsingSubSelect()) {
return $query->whereHas(
$this->getConstraint()->getRelationshipName(),
function (Builder $query): Builder {
$modifyRelationshipQueryUsing = $this->getConstraint()->getModifyRelationshipQueryUsing();
if ($modifyRelationshipQueryUsing) {
$query = $this->evaluate($modifyRelationshipQueryUsing, [
'query' => $query,
]) ?? $query;
}
$qualifiedColumn = $query->qualifyColumn($this->getConstraint()->getAttributeForQuery());
if ($this->hasQueryModificationCallback()) {
return $this->evaluate($this->modifyQueryUsing, [
'column' => $qualifiedColumn,
'qualifiedColumn' => $qualifiedColumn,
'query' => $query,
]) ?? $query;
}
return $this->apply($query, $qualifiedColumn);
},
);
}
$qualifiedColumn = $query->qualifyColumn($this->getConstraint()->getAttributeForQuery());
if ($this->hasQueryModificationCallback()) {
return $this->evaluate($this->modifyQueryUsing, [
'column' => $qualifiedColumn,
'qualifiedColumn' => $qualifiedColumn,
'query' => $query,
]) ?? $query;
}
return $this->apply($query, $qualifiedColumn);
}
public function applyToBaseFilterQuery(Builder $query): Builder
{
return $query;
}
/**
* @return array<\Filament\Schemas\Components\Component>
*/
public function getFormSchema(): array
{
return [];
}
public function constraint(?Constraint $constraint): static
{
$this->constraint = $constraint;
return $this;
}
/**
* @param array<string, mixed> | null $settings
*/
public function settings(?array $settings): static
{
$this->settings = $settings;
return $this;
}
public function inverse(?bool $condition = true): static
{
$this->isInverse = $condition;
return $this;
}
public function getConstraint(): ?Constraint
{
return $this->constraint;
}
/**
* @return array<string, mixed> | null
*/
public function getSettings(): ?array
{
return $this->settings;
}
protected function getStringSetting(string $key): ?string
{
$value = $this->getSettings()[$key] ?? null;
// Security: settings arrive from the request payload and can be tampered with,
// so a non-scalar value (e.g. an array) must not reach `trim()` / string casts
// where it would throw a `TypeError`. Fail closed by returning `null` instead.
if (! is_scalar($value)) {
return null;
}
return trim((string) $value);
}
protected function getNumericSetting(string $key): ?float
{
$value = $this->getSettings()[$key] ?? null;
// Security: settings arrive from the request payload and can be tampered with, so a
// non-numeric value (e.g. an array) must not reach `floatval()` / `Number::format()`
// where it would throw a `TypeError`. Fail closed by returning `null` instead.
if (! is_numeric($value)) {
return null;
}
return (float) $value;
}
protected function getDateSetting(string $key): ?string
{
$value = $this->getSettings()[$key] ?? null;
// Security: settings arrive from the request payload and can be tampered with, so a
// non-scalar value (e.g. an array) must not reach `Carbon::parse()` / `whereDate()`
// where it would throw a `TypeError`. Fail closed by returning `null` instead.
if (! is_scalar($value)) {
return null;
}
return (string) $value;
}
public function isInverse(): ?bool
{
return $this->isInverse;
}
public function queriesRelationshipsUsingSubSelect(): bool
{
return $this->getConstraint()->queriesRelationships();
}
protected function hasQueryModificationCallback(): bool
{
return $this->modifyQueryUsing instanceof Closure;
}
protected function hasBaseQueryModificationCallback(): bool
{
return $this->modifyBaseQueryUsing instanceof Closure;
}
protected function resolveDefaultClosureDependencyForEvaluationByName(string $parameterName): array
{
return match ($parameterName) {
'constraint' => [$this->getConstraint()],
'isInverse' => [$this->isInverse()],
'settings' => [$this->getSettings()],
default => parent::resolveDefaultClosureDependencyForEvaluationByName($parameterName),
};
}
}

View file

@ -0,0 +1,69 @@
<?php
namespace Filament\QueryBuilder\Constraints;
use Closure;
use Filament\QueryBuilder\Constraints\RelationshipConstraint\Operators\EqualsOperator;
use Filament\QueryBuilder\Constraints\RelationshipConstraint\Operators\HasMaxOperator;
use Filament\QueryBuilder\Constraints\RelationshipConstraint\Operators\HasMinOperator;
use Filament\QueryBuilder\Constraints\RelationshipConstraint\Operators\IsEmptyOperator;
use Filament\QueryBuilder\Constraints\RelationshipConstraint\Operators\IsRelatedToOperator;
use Filament\QueryBuilder\View\QueryBuilderIconAlias;
use Filament\Support\Facades\FilamentIcon;
use Filament\Support\Icons\Heroicon;
class RelationshipConstraint extends Constraint
{
protected bool | Closure $isMultiple = false;
protected bool | Closure | null $canBeEmpty = false;
protected function setUp(): void
{
parent::setUp();
$this->icon(FilamentIcon::resolve(QueryBuilderIconAlias::CONSTRAINTS_RELATIONSHIP) ?? Heroicon::ArrowsPointingOut);
$this->operators([
HasMinOperator::make()
->visible(fn (): bool => $this->isMultiple()),
HasMaxOperator::make()
->visible(fn (): bool => $this->isMultiple()),
EqualsOperator::make()
->visible(fn (): bool => $this->isMultiple()),
IsEmptyOperator::make()
->visible(fn (): bool => $this->canBeEmpty()),
]);
}
public function selectable(IsRelatedToOperator $operator): static
{
$this->unshiftOperators([$operator]);
return $this;
}
public function multiple(bool | Closure $condition = true): static
{
$this->isMultiple = $condition;
return $this;
}
public function isMultiple(): bool
{
return (bool) $this->evaluate($this->isMultiple);
}
public function emptyable(bool | Closure | null $condition = true): static
{
$this->canBeEmpty = $condition;
return $this;
}
public function canBeEmpty(): bool
{
return $this->evaluate($this->canBeEmpty) ?? $this->isMultiple();
}
}

View file

@ -0,0 +1,82 @@
<?php
namespace Filament\QueryBuilder\Constraints\RelationshipConstraint\Operators;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\TextInput;
use Filament\QueryBuilder\Constraints\Operators\Operator;
use Filament\Schemas\Components\Component;
use Illuminate\Database\Eloquent\Builder;
class EqualsOperator extends Operator
{
public function getName(): string
{
return 'equals';
}
public function getLabel(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.relationship.equals.label.inverse' :
'filament-query-builder::query-builder.operators.relationship.equals.label.direct',
);
}
public function getSummary(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.relationship.equals.summary.inverse' :
'filament-query-builder::query-builder.operators.relationship.equals.summary.direct',
[
'relationship' => $this->getConstraint()->getAttributeLabel(),
'count' => ($count = $this->getNumericSetting('count')) === null ? null : (int) $count,
],
);
}
/**
* @return array<Component | Action | ActionGroup>
*/
public function getFormSchema(): array
{
return [
TextInput::make('count')
->label(__('filament-query-builder::query-builder.operators.relationship.form.count.label'))
->numeric()
->required()
->minValue(1),
];
}
public function applyToBaseQuery(Builder $query): Builder
{
$count = $this->getNumericSetting('count');
// Security: skip applying the constraint when the tampered setting is not numeric.
if ($count === null) {
return $query;
}
$modifyRelationshipQueryUsing = $this->getConstraint()->getModifyRelationshipQueryUsing();
return $query->has(
$this->getConstraint()->getRelationshipName(),
$this->isInverse() ? '!=' : '=',
(int) $count,
'and',
function (Builder $query) use ($modifyRelationshipQueryUsing): Builder {
if ($modifyRelationshipQueryUsing) {
$query = $this->evaluate($modifyRelationshipQueryUsing, [
'query' => $query,
]) ?? $query;
}
return $query;
},
);
}
}

View file

@ -0,0 +1,82 @@
<?php
namespace Filament\QueryBuilder\Constraints\RelationshipConstraint\Operators;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\TextInput;
use Filament\QueryBuilder\Constraints\Operators\Operator;
use Filament\Schemas\Components\Component;
use Illuminate\Database\Eloquent\Builder;
class HasMaxOperator extends Operator
{
public function getName(): string
{
return 'hasMax';
}
public function getLabel(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.relationship.has_max.label.inverse' :
'filament-query-builder::query-builder.operators.relationship.has_max.label.direct',
);
}
public function getSummary(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.relationship.has_max.summary.inverse' :
'filament-query-builder::query-builder.operators.relationship.has_max.summary.direct',
[
'relationship' => $this->getConstraint()->getAttributeLabel(),
'count' => ($count = $this->getNumericSetting('count')) === null ? null : (int) $count,
],
);
}
/**
* @return array<Component | Action | ActionGroup>
*/
public function getFormSchema(): array
{
return [
TextInput::make('count')
->label(__('filament-query-builder::query-builder.operators.relationship.form.count.label'))
->numeric()
->required()
->minValue(1),
];
}
public function applyToBaseQuery(Builder $query): Builder
{
$count = $this->getNumericSetting('count');
// Security: skip applying the constraint when the tampered setting is not numeric.
if ($count === null) {
return $query;
}
$modifyRelationshipQueryUsing = $this->getConstraint()->getModifyRelationshipQueryUsing();
return $query->has(
$this->getConstraint()->getRelationshipName(),
$this->isInverse() ? '>' : '<=',
(int) $count,
'and',
function (Builder $query) use ($modifyRelationshipQueryUsing): Builder {
if ($modifyRelationshipQueryUsing) {
$query = $this->evaluate($modifyRelationshipQueryUsing, [
'query' => $query,
]) ?? $query;
}
return $query;
},
);
}
}

View file

@ -0,0 +1,82 @@
<?php
namespace Filament\QueryBuilder\Constraints\RelationshipConstraint\Operators;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\TextInput;
use Filament\QueryBuilder\Constraints\Operators\Operator;
use Filament\Schemas\Components\Component;
use Illuminate\Database\Eloquent\Builder;
class HasMinOperator extends Operator
{
public function getName(): string
{
return 'hasMin';
}
public function getLabel(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.relationship.has_min.label.inverse' :
'filament-query-builder::query-builder.operators.relationship.has_min.label.direct',
);
}
public function getSummary(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.relationship.has_min.summary.inverse' :
'filament-query-builder::query-builder.operators.relationship.has_min.summary.direct',
[
'relationship' => $this->getConstraint()->getAttributeLabel(),
'count' => ($count = $this->getNumericSetting('count')) === null ? null : (int) $count,
],
);
}
/**
* @return array<Component | Action | ActionGroup>
*/
public function getFormSchema(): array
{
return [
TextInput::make('count')
->label(__('filament-query-builder::query-builder.operators.relationship.form.count.label'))
->numeric()
->required()
->minValue(1),
];
}
public function applyToBaseQuery(Builder $query): Builder
{
$count = $this->getNumericSetting('count');
// Security: skip applying the constraint when the tampered setting is not numeric.
if ($count === null) {
return $query;
}
$modifyRelationshipQueryUsing = $this->getConstraint()->getModifyRelationshipQueryUsing();
return $query->has(
$this->getConstraint()->getRelationshipName(),
$this->isInverse() ? '<' : '>=',
(int) $count,
'and',
function (Builder $query) use ($modifyRelationshipQueryUsing): Builder {
if ($modifyRelationshipQueryUsing) {
$query = $this->evaluate($modifyRelationshipQueryUsing, [
'query' => $query,
]) ?? $query;
}
return $query;
},
);
}
}

View file

@ -0,0 +1,53 @@
<?php
namespace Filament\QueryBuilder\Constraints\RelationshipConstraint\Operators;
use Filament\QueryBuilder\Constraints\Operators\Operator;
use Illuminate\Database\Eloquent\Builder;
class IsEmptyOperator extends Operator
{
public function getName(): string
{
return 'isEmpty';
}
public function getLabel(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.relationship.is_empty.label.inverse' :
'filament-query-builder::query-builder.operators.relationship.is_empty.label.direct',
);
}
public function getSummary(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.relationship.is_empty.summary.inverse' :
'filament-query-builder::query-builder.operators.relationship.is_empty.summary.direct',
['relationship' => $this->getConstraint()->getAttributeLabel()],
);
}
public function applyToBaseQuery(Builder $query): Builder
{
$relationshipName = $this->getConstraint()->getRelationshipName();
$modifyRelationshipQueryUsing = $this->getConstraint()->getModifyRelationshipQueryUsing();
$scopeCallback = function (Builder $query) use ($modifyRelationshipQueryUsing): Builder {
if ($modifyRelationshipQueryUsing) {
$query = $this->evaluate($modifyRelationshipQueryUsing, [
'query' => $query,
]) ?? $query;
}
return $query;
};
return $this->isInverse()
? $query->has($relationshipName, '>=', 1, 'and', $scopeCallback)
: $query->doesntHave($relationshipName, 'and', $scopeCallback);
}
}

View file

@ -0,0 +1,373 @@
<?php
namespace Filament\QueryBuilder\Constraints\RelationshipConstraint\Operators;
use Closure;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\Select;
use Filament\QueryBuilder\Constraints\Operators\Operator;
use Filament\QueryBuilder\Constraints\RelationshipConstraint;
use Filament\Schemas\Components\Component;
use Filament\Support\Services\RelationshipJoiner;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\Relation;
use LogicException;
use Znck\Eloquent\Relations\BelongsToThrough;
class IsRelatedToOperator extends Operator
{
protected string | Closure | null $titleAttribute = null;
protected ?Closure $modifyRelationshipQueryUsing = null;
protected bool | Closure $isPreloaded = false;
protected bool | Closure $isMultiple = false;
protected bool | Closure $isNative = true;
protected bool | Closure $isStatic = false;
protected bool | Closure $isSearchable = false;
protected int | Closure $optionsLimit = 50;
protected bool | Closure | null $isSearchForcedCaseInsensitive = null;
protected ?Closure $getOptionLabelUsing = null;
protected ?Closure $getOptionLabelsUsing = null;
protected ?Closure $getSearchResultsUsing = null;
protected ?Closure $getOptionLabelFromRecordUsing = null;
public function getName(): string
{
return 'isRelatedTo';
}
public function getLabel(): string
{
return __(
$this->getConstraint()->isMultiple() ?
(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.relationship.is_related_to.label.multiple.inverse' :
'filament-query-builder::query-builder.operators.relationship.is_related_to.label.multiple.direct'
) :
(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.relationship.is_related_to.label.single.inverse' :
'filament-query-builder::query-builder.operators.relationship.is_related_to.label.single.direct'
),
);
}
public function getSummary(): string
{
$constraint = $this->getConstraint();
$values = $this->getValueSetting();
$relationshipQuery = $this->getRelationshipQuery();
$values = $relationshipQuery
->when(
$this->getRelationship() instanceof BelongsToThrough,
fn (Builder $query) => $query->distinct(),
)
->whereKey($values)
->pluck($relationshipQuery->qualifyColumn($this->getTitleAttribute()))
->join(glue: __('filament-query-builder::query-builder.operators.relationship.is_related_to.summary.values_glue.0'), finalGlue: __('filament-query-builder::query-builder.operators.relationship.is_related_to.summary.values_glue.final'));
return __(
$this->getConstraint()->isMultiple() ?
(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.relationship.is_related_to.summary.multiple.inverse' :
'filament-query-builder::query-builder.operators.relationship.is_related_to.summary.multiple.direct'
) :
(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.relationship.is_related_to.summary.single.inverse' :
'filament-query-builder::query-builder.operators.relationship.is_related_to.summary.single.direct'
),
[
'relationship' => $constraint->getAttributeLabel(),
'values' => $values,
],
);
}
/**
* @return array<Component | Action | ActionGroup>
*/
public function getFormSchema(): array
{
$constraint = $this->getConstraint();
$field = Select::make($constraint->isMultiple() ? 'values' : 'value')
->label(__($constraint->isMultiple() ? 'filament-query-builder::query-builder.operators.relationship.is_related_to.form.values.label' : 'filament-query-builder::query-builder.operators.relationship.is_related_to.form.value.label'))
->multiple($this->isMultiple())
->searchable($this->isSearchable())
->preload($this->isPreloaded())
->native($this->isNative())
->optionsLimit($this->getOptionsLimit())
->required()
->model($constraint->getModel())
->relationship(
$constraint->getRelationshipName(),
$this->getTitleAttribute(),
$this->modifyRelationshipQueryUsing,
)
->forceSearchCaseInsensitive($this->isSearchForcedCaseInsensitive())
->dehydrated()
->columnSpanFull();
if ($this->getOptionLabelUsing) {
$field->getOptionLabelUsing($this->getOptionLabelUsing);
}
if ($this->getOptionLabelsUsing) {
$field->getOptionLabelsUsing($this->getOptionLabelsUsing);
}
if ($this->getOptionLabelFromRecordUsing) {
$field->getOptionLabelFromRecordUsing($this->getOptionLabelFromRecordUsing);
}
if ($this->getSearchResultsUsing) {
$field->getSearchResultsUsing($this->getSearchResultsUsing);
}
return [$field];
}
public function titleAttribute(string | Closure | null $attribute): static
{
$this->titleAttribute = $attribute;
return $this;
}
public function modifyRelationshipQueryUsing(?Closure $modifyQueryUsing = null): static
{
$this->modifyRelationshipQueryUsing = $modifyQueryUsing;
return $this;
}
public function getOptionLabelUsing(?Closure $callback): static
{
$this->getOptionLabelUsing = $callback;
return $this;
}
public function getOptionLabelsUsing(?Closure $callback): static
{
$this->getOptionLabelsUsing = $callback;
return $this;
}
public function getSearchResultsUsing(?Closure $callback): static
{
$this->getSearchResultsUsing = $callback;
return $this;
}
public function apply(Builder $query, string $qualifiedColumn): Builder
{
$constraint = $this->getConstraint();
$value = $this->getValueSetting();
// Security: nothing valid remains to filter by after discarding tampered values.
if (($value === null) || ($value === [])) {
return $query;
}
return $query->{$this->isInverse() ? 'whereDoesntHave' : 'whereHas'}(
$constraint->getRelationshipName(),
function (Builder $query) use ($value): Builder {
if ($this->modifyRelationshipQueryUsing) {
$query = $this->evaluate($this->modifyRelationshipQueryUsing, [
'query' => $query,
]) ?? $query;
}
return $query->whereKey($value);
},
);
}
protected function getValueSetting(): mixed
{
$value = $this->getSettings()[$this->getConstraint()->isMultiple() ? 'values' : 'value'] ?? null;
// Security: settings arrive from the request payload and can be tampered with. The value
// may be a scalar key or a list of scalar keys, depending on whether the operator is
// `multiple()`, but any other shape (e.g. a nested array) would reach `whereKey()`
// binding and crash the request. Fail closed by discarding non-scalar values.
if (is_array($value)) {
return array_values(array_filter($value, is_scalar(...)));
}
return is_scalar($value) ? $value : null;
}
public function getConstraint(): ?RelationshipConstraint
{
$constraint = parent::getConstraint();
if (! $constraint) {
return null;
}
if (! ($constraint instanceof RelationshipConstraint)) {
throw new LogicException('Is operator can only be used with relationship constraints.');
}
return $constraint;
}
public function forceSearchCaseInsensitive(bool | Closure | null $condition = true): static
{
$this->isSearchForcedCaseInsensitive = $condition;
return $this;
}
public function isSearchForcedCaseInsensitive(): ?bool
{
return $this->evaluate($this->isSearchForcedCaseInsensitive);
}
public function getModifyRelationshipQueryUsing(): ?Closure
{
return $this->modifyRelationshipQueryUsing;
}
public function getRelationship(): Relation | Builder
{
$constraint = $this->getConstraint();
$record = app($constraint->getModel());
$relationship = null;
foreach (explode('.', $constraint->getRelationshipName()) as $nestedRelationshipName) {
if ($record->hasAttribute($nestedRelationshipName)) {
$relationship = null;
break;
}
if (! $record->isRelation($nestedRelationshipName)) {
$relationship = null;
break;
}
$relationship = $record->{$nestedRelationshipName}();
$record = $relationship->getRelated();
}
return $relationship;
}
public function getRelationshipQuery(): ?Builder
{
$relationship = Relation::noConstraints(fn () => $this->getRelationship());
$relationshipQuery = app(RelationshipJoiner::class)->prepareQueryForNoConstraints($relationship);
if ($this->getModifyRelationshipQueryUsing()) {
$relationshipQuery = $this->evaluate($this->modifyRelationshipQueryUsing, [
'query' => $relationshipQuery,
]) ?? $relationshipQuery;
}
if (empty($relationshipQuery->getQuery()->orders)) {
$relationshipQuery->orderBy($relationshipQuery->qualifyColumn($this->getTitleAttribute()));
}
return $relationshipQuery;
}
public function getTitleAttribute(): ?string
{
return $this->evaluate($this->titleAttribute);
}
public function multiple(bool | Closure $condition = true): static
{
$this->isMultiple = $condition;
return $this;
}
public function isMultiple(): bool
{
return (bool) $this->evaluate($this->isMultiple);
}
public function searchable(bool | Closure $condition = true): static
{
$this->isSearchable = $condition;
return $this;
}
public function isSearchable(): bool
{
return (bool) $this->evaluate($this->isSearchable);
}
public function optionsLimit(int | Closure $limit): static
{
$this->optionsLimit = $limit;
return $this;
}
public function getOptionsLimit(): int
{
return $this->evaluate($this->optionsLimit);
}
public function native(bool | Closure $condition = true): static
{
$this->isNative = $condition;
return $this;
}
public function isNative(): bool
{
return (bool) $this->evaluate($this->isNative);
}
public function getOptionLabelFromRecordUsing(?Closure $callback): static
{
$this->getOptionLabelFromRecordUsing = $callback;
return $this;
}
public function preload(bool | Closure $condition = true): static
{
$this->isPreloaded = $condition;
return $this;
}
public function isPreloaded(): bool
{
return (bool) $this->evaluate($this->isPreloaded);
}
}

View file

@ -0,0 +1,191 @@
<?php
namespace Filament\QueryBuilder\Constraints;
use Closure;
use Filament\QueryBuilder\Constraints\Operators\IsFilledOperator;
use Filament\QueryBuilder\Constraints\SelectConstraint\Operators\IsOperator;
use Filament\QueryBuilder\View\QueryBuilderIconAlias;
use Filament\Support\Contracts\HasLabel as LabelInterface;
use Filament\Support\Facades\FilamentIcon;
use Filament\Support\Icons\Heroicon;
use Illuminate\Contracts\Support\Arrayable;
use UnitEnum;
class SelectConstraint extends Constraint
{
use Concerns\CanBeNullable;
protected bool | Closure $isMultiple = false;
protected bool | Closure $isNative = true;
protected bool | Closure $isSearchable = false;
protected int | Closure $optionsLimit = 50;
protected ?Closure $getOptionLabelFromRecordUsing = null;
/**
* @var array<string | array<string>> | Arrayable | class-string | Closure | null
*/
protected array | Arrayable | string | Closure | null $options = null;
protected ?Closure $getOptionLabelUsing = null;
protected ?Closure $getOptionLabelsUsing = null;
protected ?Closure $getSearchResultsUsing = null;
protected function setUp(): void
{
parent::setUp();
$this->icon(FilamentIcon::resolve(QueryBuilderIconAlias::CONSTRAINTS_SELECT) ?? Heroicon::ChevronUpDown);
$this->operators([
IsOperator::class,
IsFilledOperator::make()
->visible(fn (): bool => $this->isNullable()),
]);
}
public function multiple(bool | Closure $condition = true): static
{
$this->isMultiple = $condition;
return $this;
}
public function searchable(bool | Closure $condition = true): static
{
$this->isSearchable = $condition;
return $this;
}
public function isMultiple(): bool
{
return (bool) $this->evaluate($this->isMultiple);
}
public function isSearchable(): bool
{
return (bool) $this->evaluate($this->isSearchable);
}
public function optionsLimit(int | Closure $limit): static
{
$this->optionsLimit = $limit;
return $this;
}
public function getOptionsLimit(): int
{
return $this->evaluate($this->optionsLimit);
}
public function native(bool | Closure $condition = true): static
{
$this->isNative = $condition;
return $this;
}
public function isNative(): bool
{
return (bool) $this->evaluate($this->isNative);
}
public function getOptionLabelFromRecordUsing(?Closure $callback): static
{
$this->getOptionLabelFromRecordUsing = $callback;
return $this;
}
public function getOptionLabelFromRecordUsingCallback(): ?Closure
{
return $this->getOptionLabelFromRecordUsing;
}
/**
* @param array<string | array<string>> | Arrayable | class-string | Closure | null $options
*/
public function options(array | Arrayable | string | Closure | null $options): static
{
$this->options = $options;
return $this;
}
/**
* @return array<string | array<string>>
*/
public function getOptions(): array
{
$options = $this->evaluate($this->options);
if (
is_string($options) &&
enum_exists($enum = $options)
) {
if (is_a($enum, LabelInterface::class, allow_string: true)) {
return array_reduce($enum::cases(), function (array $carry, LabelInterface & UnitEnum $case): array {
$carry[$case->value ?? $case->name] = $case->getLabel() ?? $case->name;
return $carry;
}, []);
}
return array_reduce($enum::cases(), function (array $carry, UnitEnum $case): array {
$carry[$case->value ?? $case->name] = $case->name;
return $carry;
}, []);
}
if ($options instanceof Arrayable) {
$options = $options->toArray();
}
return $options ?? [];
}
public function getOptionLabelUsing(?Closure $callback): static
{
$this->getOptionLabelUsing = $callback;
return $this;
}
public function getOptionLabelsUsing(?Closure $callback): static
{
$this->getOptionLabelsUsing = $callback;
return $this;
}
public function getSearchResultsUsing(?Closure $callback): static
{
$this->getSearchResultsUsing = $callback;
return $this;
}
public function getOptionLabelUsingCallback(): ?Closure
{
return $this->getOptionLabelUsing;
}
public function getOptionLabelsUsingCallback(): ?Closure
{
return $this->getOptionLabelsUsing;
}
public function getSearchResultsUsingCallback(): ?Closure
{
return $this->getSearchResultsUsing;
}
}

View file

@ -0,0 +1,152 @@
<?php
namespace Filament\QueryBuilder\Constraints\SelectConstraint\Operators;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\Select;
use Filament\QueryBuilder\Constraints\Operators\Operator;
use Filament\QueryBuilder\Constraints\SelectConstraint;
use Filament\Schemas\Components\Component;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Arr;
use LogicException;
class IsOperator extends Operator
{
public function getName(): string
{
return 'is';
}
public function getLabel(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.select.is.label.inverse' :
'filament-query-builder::query-builder.operators.select.is.label.direct',
);
}
public function getSummary(): string
{
$constraint = $this->getConstraint();
if ($constraint->isMultiple()) {
$getLabels = $constraint->getOptionLabelsUsingCallback();
$valuesKey = 'values';
} else {
$getLabels = $constraint->getOptionLabelUsingCallback();
$valuesKey = 'value';
}
$values = $this->getValueSetting();
$labels = $getLabels ?
Arr::wrap($this->evaluate($getLabels, [$valuesKey => $values])) :
Arr::only($constraint->getOptions(), Arr::wrap($values));
$joinedValues = Arr::join(
$labels,
glue: __('filament-query-builder::query-builder.operators.select.is.summary.values_glue.0'),
finalGlue: __('filament-query-builder::query-builder.operators.select.is.summary.values_glue.final'),
);
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.select.is.summary.inverse' :
'filament-query-builder::query-builder.operators.select.is.summary.direct',
[
'attribute' => $constraint->getAttributeLabel(),
'values' => $joinedValues,
],
);
}
/**
* @return array<Component | Action | ActionGroup>
*/
public function getFormSchema(): array
{
$constraint = $this->getConstraint();
$field = Select::make($constraint->isMultiple() ? 'values' : 'value')
->label(__($constraint->isMultiple() ? 'filament-query-builder::query-builder.operators.select.is.form.values.label' : 'filament-query-builder::query-builder.operators.select.is.form.value.label'))
->options($constraint->getOptions())
->multiple($constraint->isMultiple())
->searchable($constraint->isSearchable())
->native($constraint->isNative())
->optionsLimit($constraint->getOptionsLimit())
->required()
->columnSpanFull();
if ($getOptionLabelUsing = $constraint->getOptionLabelUsingCallback()) {
$field->getOptionLabelUsing($getOptionLabelUsing);
}
if ($getOptionLabelsUsing = $constraint->getOptionLabelsUsingCallback()) {
$field->getOptionLabelsUsing($getOptionLabelsUsing);
}
if ($getOptionLabelFromRecordUsing = $constraint->getOptionLabelFromRecordUsingCallback()) {
$field->getOptionLabelFromRecordUsing($getOptionLabelFromRecordUsing);
}
if ($getSearchResultsUsing = $constraint->getSearchResultsUsingCallback()) {
$field->getSearchResultsUsing($getSearchResultsUsing);
}
return [$field];
}
public function apply(Builder $query, string $qualifiedColumn): Builder
{
$value = $this->getValueSetting();
if (is_array($value)) {
// Security: nothing valid remains to filter by after discarding tampered values.
if ($value === []) {
return $query;
}
return $query->{$this->isInverse() ? 'whereNotIn' : 'whereIn'}($qualifiedColumn, $value);
}
// Security: skip applying the constraint when the tampered single value is not a scalar.
if ($value === null) {
return $query;
}
return $query->{$this->isInverse() ? 'whereNot' : 'where'}($qualifiedColumn, $value);
}
protected function getValueSetting(): mixed
{
$isMultiple = $this->getConstraint()->isMultiple();
$value = $this->getSettings()[$isMultiple ? 'values' : 'value'] ?? null;
// Security: settings arrive from the request payload and can be tampered with. A single
// select value must be a scalar, and a multiple select value must be a list of scalars;
// any other shape (e.g. a nested array) would reach `strval()` / `Arr::only()` and throw.
// Fail closed by discarding non-scalar values.
if ($isMultiple) {
return is_array($value)
? array_values(array_filter($value, is_scalar(...)))
: [];
}
return is_scalar($value) ? $value : null;
}
public function getConstraint(): ?SelectConstraint
{
$constraint = parent::getConstraint();
if (! ($constraint instanceof SelectConstraint)) {
throw new LogicException('Is operator can only be used with select constraints.');
}
return $constraint;
}
}

View file

@ -0,0 +1,33 @@
<?php
namespace Filament\QueryBuilder\Constraints;
use Filament\QueryBuilder\Constraints\Operators\IsFilledOperator;
use Filament\QueryBuilder\Constraints\TextConstraint\Operators\ContainsOperator;
use Filament\QueryBuilder\Constraints\TextConstraint\Operators\EndsWithOperator;
use Filament\QueryBuilder\Constraints\TextConstraint\Operators\EqualsOperator;
use Filament\QueryBuilder\Constraints\TextConstraint\Operators\StartsWithOperator;
use Filament\QueryBuilder\View\QueryBuilderIconAlias;
use Filament\Support\Facades\FilamentIcon;
use Filament\Support\Icons\Heroicon;
class TextConstraint extends Constraint
{
use Concerns\CanBeNullable;
protected function setUp(): void
{
parent::setUp();
$this->icon(FilamentIcon::resolve(QueryBuilderIconAlias::CONSTRAINTS_TEXT) ?? Heroicon::Language);
$this->operators([
ContainsOperator::class,
StartsWithOperator::class,
EndsWithOperator::class,
EqualsOperator::class,
IsFilledOperator::make()
->visible(fn (): bool => $this->isNullable()),
]);
}
}

View file

@ -0,0 +1,97 @@
<?php
namespace Filament\QueryBuilder\Constraints\TextConstraint\Operators;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\TextInput;
use Filament\QueryBuilder\Constraints\Operators\Operator;
use Filament\Schemas\Components\Component;
use Illuminate\Database\Connection;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\Expression;
use Illuminate\Support\Str;
class ContainsOperator extends Operator
{
public function getName(): string
{
return 'contains';
}
public function getLabel(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.text.contains.label.inverse' :
'filament-query-builder::query-builder.operators.text.contains.label.direct',
);
}
public function getSummary(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.text.contains.summary.inverse' :
'filament-query-builder::query-builder.operators.text.contains.summary.direct',
[
'attribute' => $this->getConstraint()->getAttributeLabel(),
'text' => $this->getStringSetting('text'),
],
);
}
/**
* @return array<Component | Action | ActionGroup>
*/
public function getFormSchema(): array
{
return [
TextInput::make('text')
->label(__('filament-query-builder::query-builder.operators.text.form.text.label'))
->required()
->columnSpanFull(),
];
}
public function apply(Builder $query, string $qualifiedColumn): Builder
{
// Security: skip applying the constraint when the tampered setting is not a scalar string.
$text = $this->getStringSetting('text');
if ($text === null) {
return $query;
}
/** @var Connection $databaseConnection */
$databaseConnection = $query->getConnection();
$isPostgres = $databaseConnection->getDriverName() === 'pgsql';
if ($isPostgres) {
$parts = explode('.', $qualifiedColumn);
if (count($parts) === 3) {
[$schema, $table, $column] = $parts;
$table = "{$schema}.{$table}";
} else {
[$table, $column] = $parts;
}
if (Str::lower($table) !== $table) {
$table = collect(explode('.', $table))
->map(fn (string $segment): string => "\"{$segment}\"")
->implode('.');
}
if (Str::lower($column) !== $column) {
$column = "\"{$column}\"";
}
$qualifiedColumn = new Expression("lower({$table}.{$column}::text)");
$text = Str::lower($text);
}
return $query->{$this->isInverse() ? 'whereNot' : 'where'}($qualifiedColumn, 'like', "%{$text}%");
}
}

View file

@ -0,0 +1,97 @@
<?php
namespace Filament\QueryBuilder\Constraints\TextConstraint\Operators;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\TextInput;
use Filament\QueryBuilder\Constraints\Operators\Operator;
use Filament\Schemas\Components\Component;
use Illuminate\Database\Connection;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\Expression;
use Illuminate\Support\Str;
class EndsWithOperator extends Operator
{
public function getName(): string
{
return 'endsWith';
}
public function getLabel(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.text.ends_with.label.inverse' :
'filament-query-builder::query-builder.operators.text.ends_with.label.direct',
);
}
public function getSummary(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.text.ends_with.summary.inverse' :
'filament-query-builder::query-builder.operators.text.ends_with.summary.direct',
[
'attribute' => $this->getConstraint()->getAttributeLabel(),
'text' => $this->getStringSetting('text'),
],
);
}
/**
* @return array<Component | Action | ActionGroup>
*/
public function getFormSchema(): array
{
return [
TextInput::make('text')
->label(__('filament-query-builder::query-builder.operators.text.form.text.label'))
->required()
->columnSpanFull(),
];
}
public function apply(Builder $query, string $qualifiedColumn): Builder
{
// Security: skip applying the constraint when the tampered setting is not a scalar string.
$text = $this->getStringSetting('text');
if ($text === null) {
return $query;
}
/** @var Connection $databaseConnection */
$databaseConnection = $query->getConnection();
$isPostgres = $databaseConnection->getDriverName() === 'pgsql';
if ($isPostgres) {
$parts = explode('.', $qualifiedColumn);
if (count($parts) === 3) {
[$schema, $table, $column] = $parts;
$table = "{$schema}.{$table}";
} else {
[$table, $column] = $parts;
}
if (Str::lower($table) !== $table) {
$table = collect(explode('.', $table))
->map(fn (string $segment): string => "\"{$segment}\"")
->implode('.');
}
if (Str::lower($column) !== $column) {
$column = "\"{$column}\"";
}
$qualifiedColumn = new Expression("lower({$table}.{$column}::text)");
$text = Str::lower($text);
}
return $query->{$this->isInverse() ? 'whereNot' : 'where'}($qualifiedColumn, 'like', "%{$text}");
}
}

View file

@ -0,0 +1,97 @@
<?php
namespace Filament\QueryBuilder\Constraints\TextConstraint\Operators;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\TextInput;
use Filament\QueryBuilder\Constraints\Operators\Operator;
use Filament\Schemas\Components\Component;
use Illuminate\Database\Connection;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\Expression;
use Illuminate\Support\Str;
class EqualsOperator extends Operator
{
public function getName(): string
{
return 'equals';
}
public function getLabel(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.text.equals.label.inverse' :
'filament-query-builder::query-builder.operators.text.equals.label.direct',
);
}
public function getSummary(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.text.equals.summary.inverse' :
'filament-query-builder::query-builder.operators.text.equals.summary.direct',
[
'attribute' => $this->getConstraint()->getAttributeLabel(),
'text' => $this->getStringSetting('text'),
],
);
}
/**
* @return array<Component | Action | ActionGroup>
*/
public function getFormSchema(): array
{
return [
TextInput::make('text')
->label(__('filament-query-builder::query-builder.operators.text.form.text.label'))
->required()
->columnSpanFull(),
];
}
public function apply(Builder $query, string $qualifiedColumn): Builder
{
// Security: skip applying the constraint when the tampered setting is not a scalar string.
$text = $this->getStringSetting('text');
if ($text === null) {
return $query;
}
/** @var Connection $databaseConnection */
$databaseConnection = $query->getConnection();
$isPostgres = $databaseConnection->getDriverName() === 'pgsql';
if ($isPostgres) {
$parts = explode('.', $qualifiedColumn);
if (count($parts) === 3) {
[$schema, $table, $column] = $parts;
$table = "{$schema}.{$table}";
} else {
[$table, $column] = $parts;
}
if (Str::lower($table) !== $table) {
$table = collect(explode('.', $table))
->map(fn (string $segment): string => "\"{$segment}\"")
->implode('.');
}
if (Str::lower($column) !== $column) {
$column = "\"{$column}\"";
}
$qualifiedColumn = new Expression("lower({$table}.{$column}::text)");
$text = Str::lower($text);
}
return $query->{$this->isInverse() ? 'whereNot' : 'where'}($qualifiedColumn, 'like', $text);
}
}

View file

@ -0,0 +1,97 @@
<?php
namespace Filament\QueryBuilder\Constraints\TextConstraint\Operators;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\TextInput;
use Filament\QueryBuilder\Constraints\Operators\Operator;
use Filament\Schemas\Components\Component;
use Illuminate\Database\Connection;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\Expression;
use Illuminate\Support\Str;
class StartsWithOperator extends Operator
{
public function getName(): string
{
return 'startsWith';
}
public function getLabel(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.text.starts_with.label.inverse' :
'filament-query-builder::query-builder.operators.text.starts_with.label.direct',
);
}
public function getSummary(): string
{
return __(
$this->isInverse() ?
'filament-query-builder::query-builder.operators.text.starts_with.summary.inverse' :
'filament-query-builder::query-builder.operators.text.starts_with.summary.direct',
[
'attribute' => $this->getConstraint()->getAttributeLabel(),
'text' => $this->getStringSetting('text'),
],
);
}
/**
* @return array<Component | Action | ActionGroup>
*/
public function getFormSchema(): array
{
return [
TextInput::make('text')
->label(__('filament-query-builder::query-builder.operators.text.form.text.label'))
->required()
->columnSpanFull(),
];
}
public function apply(Builder $query, string $qualifiedColumn): Builder
{
// Security: skip applying the constraint when the tampered setting is not a scalar string.
$text = $this->getStringSetting('text');
if ($text === null) {
return $query;
}
/** @var Connection $databaseConnection */
$databaseConnection = $query->getConnection();
$isPostgres = $databaseConnection->getDriverName() === 'pgsql';
if ($isPostgres) {
$parts = explode('.', $qualifiedColumn);
if (count($parts) === 3) {
[$schema, $table, $column] = $parts;
$table = "{$schema}.{$table}";
} else {
[$table, $column] = $parts;
}
if (Str::lower($table) !== $table) {
$table = collect(explode('.', $table))
->map(fn (string $segment): string => "\"{$segment}\"")
->implode('.');
}
if (Str::lower($column) !== $column) {
$column = "\"{$column}\"";
}
$qualifiedColumn = new Expression("lower({$table}.{$column}::text)");
$text = Str::lower($text);
}
return $query->{$this->isInverse() ? 'whereNot' : 'where'}($qualifiedColumn, 'like', "{$text}%");
}
}