Skip to content

Instantly share code, notes, and snippets.

@sebdesign
Last active November 7, 2016 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebdesign/ed895afccc3514af07b69f568a2f7b0f to your computer and use it in GitHub Desktop.
Save sebdesign/ed895afccc3514af07b69f568a2f7b0f to your computer and use it in GitHub Desktop.
Collection macro for invoking methods on (nested) items
<?php
use Illuminate\Support\Collection;
/**
* Invoke the method each (nested) item of the collection, returning the result of each invoked method.
*
* @var string $method The method or the path of the method separated with @.
* @var mixed $arguments,... Any optional arguments to pass to the invoked method.
* @return static
*/
Collection::macro('invoke', function ($method, ...$arguments) {
$segments = explode('@', $method);
if (count($segments) == 2) {
$path = $segments[0];
$method = $segments[1];
return $this->pluck($path)->invoke($method, ...$arguments)->collapse();
}
return $this->map(function ($item) use ($method, $arguments) {
return call_user_func([$item, $method], ...$arguments);
})
});
// Before
$friends->map(function ($friend) use ($location) {
return $friend->isNear($location);
});
// After
$friends->invoke('isNear', $location);
// Before
$friends->map(function ($friend) use ($location) {
return $friend->location->getDistanceFrom($location);
});
// After
$friends->invoke('location@getDistanceFrom', $location);
@sebdesign
Copy link
Author

Inspired from lodash's invokeMap.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment