[12.x] Extends AsCollection
to map through a closure
#55611
Closed
+51
−4
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Feature
The aim of this code is to be able to provide a closure to the
$map
parameter of theAsCollection::of()
andAsCollection::using()
methods, in order to be able to fully customize the creation of each item inside the collection.As casts needs to be serializable, I used the
SerializableClosure
in case a closure is used for the $map parameter.I also extends this feature to the
AsEncryptedCollection
class:Context
I want to use this new
$map
parameter (from the recent PR #55383) to generate a collection of data objects created with spatie/laravel-data, that are very well-suited for Eloquent casting. This is what I tried:To instantiate the data objects with the
from()
method, theCollection::map()
method is used, which callsarray_map([DataObject::class, 'from'], $array, $keys)
internally. However, as the$keys
are passed, thefrom()
method thinks that these are properties of theDataObject
, which is not.With a closure, I would be able to do that to makes spatie/laravel-data objects works: