[10.x] Add Collection::enforce() method#47785
Conversation
|
The way this is worded, I would expect // guarding against incorrect additions
$intCollection = collect()->enforce('int');
$int->push('hello world');
// coercion
$users = User::get();
$usersArray = $users->enforce('array');Not proposing that either needs to be added, but maybe it being named something other than "enforce" would provide greater specificity. It really is type assertion, not enforcement. |
|
@inxilpro can you rebase against 10.x? |
@cosmastech my hope is that it will eventually be possible to attach a type to the Collection and have it be enforced for future items as well (like the current Eloquent Collection implementation). This is a first step towards that. Baby steps :) |
|
It's also worth mentioning that this PR was the brainchild of @vanere at Laracon. We were talking about it during the afterparty and decided to just write the code then-and-there. It was pretty fun—a few other Laracon attendees peeked at the code and gave feedback on the implementation :) |
|
Perhaps to not make it feel like it will continue to only allow a particular type,
|
|
I like ensure! I’ll update tonight or tomorrow. |
|
❤️ |
|
Thanks |
This adds a new
Collection::enforce()method that enforces the type of all items in the collection (and also applies type annotations). This allows for the following code:It also means that for developers who use an IDE that parses type annotations, calling
enforcewill also enable code intelligence: