Skip to content

Commit fc1ce8e

Browse files
authored
fix: filter years before account creation (DenverCoder1#449)
1 parent 9c49f62 commit fc1ce8e

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

src/stats.php

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ function buildContributionGraphQuery(string $user, int $year): string
1515
$end = "$year-12-31T23:59:59Z";
1616
return "query {
1717
user(login: \"$user\") {
18+
createdAt
1819
contributionsCollection(from: \"$start\", to: \"$end\") {
1920
contributionYears
2021
contributionCalendar {
@@ -122,17 +123,25 @@ function getContributionGraphs(string $user): array
122123
// get the list of years the user has contributed and the current year's contribution graph
123124
$currentYear = intval(date("Y"));
124125
$responses = executeContributionGraphRequests($user, [$currentYear]);
125-
$contributionYears = $responses[$currentYear]->data->user->contributionsCollection->contributionYears ?? [];
126+
// get user's created date (YYYY-MM-DDTHH:MM:SSZ format)
127+
$userCreatedDateTimeString = $responses[$currentYear]->data->user->createdAt ?? null;
126128
// if there are no contribution years, an API error must have occurred
127-
if (empty($contributionYears)) {
129+
if (empty($userCreatedDateTimeString)) {
128130
throw new AssertionError("Failed to retrieve contributions. This is likely a GitHub API issue.", 500);
129131
}
130-
// remove the current year from the list since it's already been fetched
131-
$contributionYears = array_filter($contributionYears, function ($year) use ($currentYear) {
132-
return $year !== $currentYear;
133-
});
132+
// extract the year from the created datetime string
133+
$userCreatedYear = intval(explode("-", $userCreatedDateTimeString)[0]);
134+
// create an array of years from the user's created year to one year before the current year
135+
$yearsToRequest = range($userCreatedYear, $currentYear - 1);
136+
// also check the first contribution year if the year is before 2005 (the year Git was created)
137+
// since the user may have backdated some commits to a specific year such as 1970 (see #448)
138+
$contributionYears = $responses[$currentYear]->data->user->contributionsCollection->contributionYears ?? [];
139+
$firstContributionYear = $contributionYears[count($contributionYears) - 1] ?? $userCreatedYear;
140+
if ($firstContributionYear < 2005) {
141+
array_unshift($yearsToRequest, $firstContributionYear);
142+
}
134143
// get the contribution graphs for the previous years
135-
$responses += executeContributionGraphRequests($user, $contributionYears);
144+
$responses += executeContributionGraphRequests($user, $yearsToRequest);
136145
return $responses;
137146
}
138147

0 commit comments

Comments
 (0)