FnChain is an experimental helper I came up when dealing with following nesting closure:
return $query
->where('is_enabled', true)
->where('available_from', '<=', DB::raw('NOW()'))
->where(
fn (Builder $q) => $q
->whereNull('available_until')
->orWhere(
fn (Builder $q) => $q
->whereNotNull('available_until')
->where('available_until', '>', DB::raw('NOW()'))
)
);
I want to avoid fn (Builder $q) => $q
.
With FnChain
, above code can be rewrite to:
return $query
->where('is_enabled', true)
->where('available_from', '<=', DB::raw('NOW()'))
->where(
FnChain
::whereNull('available_until')
->orWhere(
FnChain
::whereNotNull('available_until')
->where('available_until', '>', DB::raw('NOW()'))
->toClosure()
)
->toClosure()
);
But the toClosure
is anoying me, maybe we can use Closure::fromCallable
to get ride of it?
return $query
->where('is_enabled', true)
->where('available_from', '<=', DB::raw('NOW()'))
->where(Closure::fromCallable(
FnChain
::whereNull('available_until')
->orWhere(Closure::fromCallable(
FnChain
::whereNotNull('available_until')
->where('available_until', '>', DB::raw('NOW()'))
))
));