April 15, 2018 —John Koster
The transform
helper function is used to modify the provided value if the value contains a "non-empty" value. A value is considered to be "empty" or "blank" if it meets one of the following conditions:
null
,0
,boolean
value,Countable
object and contains no items,empty
evaluates to true
If the provided value is not empty, it will be passed as an argument to the $callback
parameter and the results returned. If the value is empty, the value supplied for the $default
parameter will be returned, which itself can be an anonymous function.
The signature of the transform
method is:
1function transform(2 $value,3 callable $callback,4 $default = null5);
In the with
helper function section we implemented a getWeatherForecast
function that will return the forecast for a provided location. However, that implementation does not take into account when the Yahoo weather API returns an empty forecast, either because the API call failed, or the user supplied an invalid location.
We could handle this using a variety of if
control statements, but we will use the transform
helper function to help us control the output of the getWeatherForecast
function when these situations arise:
1/** 2 * Returns a weather forecast for a given place. 3 * 4 * @param string $place 5 * @return \Illuminate\Support\Collection 6 */ 7function getWeatherForecast($place) { 8 return with($place, function ($place) { 9 $apiUrl = 'https://query.yahooapis.com/v1/' .10 'public/yql?q=select%20*%20from%20weather.' .11 'forecast%20where%20woeid%20in%20(select' .12 '%20woeid%20from%20geo.places(1)%20where' .13 '%20text%3D%22<PLACE>%22)&format=json&env=' .14 'store%3A%2F%2Fdatatables.org' .15 '%2Falltableswithkeys';16 17 $apiUrl = str_replace(18 '<PLACE>',19 $place,20 $apiUrl21 );22 23 return with(24 new GuzzleHttp\Client,25 function ($client) use ($apiUrl) {26 /** @var GuzzleHttp\Client $client */27 $response = $client->get($apiUrl);28 $responseBody = $response->getBody();29 $result = json_decode(30 $responseBody31 ->getContents()32 );33 34 // Get the forecast. We will use the35 // the transform function to help36 // return an empty collection37 // for no forecast results.38 return transform(39 $result->query->results,40 41 // Return API forecast.42 function ($results) {43 return collect(44 $results->channel45 ->item46 ->forecast47 );48 },49 50 // Return empty collection.51 function ($results) {52 return collect();53 });54 });55 });56}
∎
The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.