Last active
November 7, 2016 15:37
-
-
Save sebdesign/ed895afccc3514af07b69f568a2f7b0f to your computer and use it in GitHub Desktop.
Collection macro for invoking methods on (nested) items
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired from lodash's invokeMap.