Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[9.x] Add Conditionable support for callback conditions #37667

Merged
merged 4 commits into from
Jun 17, 2021

Conversation

JosephSilber
Copy link
Member

@JosephSilber JosephSilber commented Jun 11, 2021

This allows passing a Closure as the conditional to when and unless:

return $this->getOptions()
    ->unless(fn ($options) => $options->has('share'))
    ->put('share', true);

Or even using a higher order collection proxy:

return $this->getOptions()
    ->unless->has('share')
    ->put('share', true);

❤️


Here's a real-world example, converting @jbrooksuk's Forge code snippet from this:

$jobData = $payload['data'];

if (! isset($jobData['initiated_by'])) {
    $jobData = array_merge($payload['data'], array_filter([
        'initiated_by' => request()->user()->id ?? null,
    ]));
}

return ['data' => $jobData];

...to a collection pipeline:

return collect($payload['data'])
    ->unless->has('initiated_by')
    ->put('initiated_by', request()->user()->id ?? null)
    ->filter()
    ->pipe(fn ($data) => ['data' => $data->all()]);

😄


Note: this includes a little breaking change. Previously, passing a closure would always be considered truthy, and wouldn't be executed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants