Skip to content

Conversation

@JosephSilber
Copy link
Contributor

@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