Skip to content

Instantly share code, notes, and snippets.

@damms005
Last active August 28, 2020 16:00
Show Gist options
  • Save damms005/1183a7160f2d8a53e63365b8155c90ed to your computer and use it in GitHub Desktop.
Save damms005/1183a7160f2d8a53e63365b8155c90ed to your computer and use it in GitHub Desktop.
Peace First Code Sample - Best Award Project
<?php
/**
* Hypothetical case: Peace First wants to select a project from the PEACE FIRST CHALLENGE for a special award.
* This selection is intended to be purely based on merit, without any bias.
*
* Assumption: For scalability reasons, the Peace First Challenge projects are hosted on another server linked to a subdomain
* via CNAME DNS entry. Hence, the endpoint to fetch all of these projects is https://api.peacefirst.org/projects/index.
* The allowed request type is GET, and fetching all available projects in one request does not
* constitute any performance issues. The payload response from this endpoint is an array of
* project objects, like below:
* [
* {
* id: 123,
* user_id: 456,
* project_name: "Menstruate and Educate",
* number_of_lives_touched: 12345,
* number_of_awards_received: 12345,
* created_at: "2020-08-25"
* },
* ...
* ]
*
* Each project is scored by getting a sum of the number of lives touched/impacted and the number of external
* awards received. The project that has the highest number of such score will be selected as the
* winning project. When there is a tie, the oldest project wins.
*/
class PeaceFirstAward
{
/**
* Computes and the winning project
*
* @return array An array containing the properties of the winning project
*/
public static function getWinningProject(): array
{
$projects = collect(self::getProjects())
->map(function (array $project) {
$project['score_points'] = (int) ($project['number_of_awards_received'] + $project['number_of_lives_touched']);
return $project;
});
$winningProject = $projects->sortByDesc('score_points')->first();
//Eliminate ties
$winningProject = $projects->where('score_points', $winningProject['score_points'])
->sortByDesc('created_at')
->first();
return $winningProject;
}
private static function getProjects(): array
{
$response = \Illuminate\Support\Facades\Http::get("https://api.peacefirst.org/projects/index");
if ($response->ok() && $response->successful()) {
return $response->json();
}
$response->throw();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment