-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub_api.php
More file actions
398 lines (332 loc) · 13.2 KB
/
Copy pathgithub_api.php
File metadata and controls
398 lines (332 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
<?php
/**
* GitHub API Service
* Handles fetching repositories from GitHub API with separation of owned and contributed repos
* Filters: Blacklist support, sorted by stars, no code display (README only)
* For contributed repos: Shows original repo, not forks. Shows user's fork link if public.
*/
require_once __DIR__ . '/config/env_loader.php';
class GitHubAPIService {
private string $username;
private ?string $token;
private string $apiUrl;
private array $hiddenProjects;
public function __construct() {
$this->username = getenv('GITHUB_USERNAME') ?: 'Samuel-Mencke';
$this->token = getenv('GITHUB_TOKEN') ?: null;
$this->apiUrl = 'https://api.github.com';
// Parse hidden projects from env (comma-separated)
$hiddenEnv = getenv('HIDDEN_PROJECTS') ?: '';
$this->hiddenProjects = array_map('trim', explode(',', $hiddenEnv));
// Always hide username/username (profile README)
$this->hiddenProjects[] = $this->username;
}
/**
* Fetch both owned and contributed repositories, sorted by stars
*
* @return array ['owned' => [...], 'contributed' => [...]]
*/
public function fetchRepositories(): array {
$owned = $this->fetchOwnedRepositories();
$contributed = $this->fetchContributedRepositories();
// Get IDs of owned repos to filter out duplicates
$ownedIds = array_column($owned, 'id');
// Filter contributed repos - remove any that are already in owned
$contributed = array_filter($contributed, function($repo) use ($ownedIds) {
return !in_array($repo['id'], $ownedIds);
});
// Re-index array after filtering
$contributed = array_values($contributed);
// Sort both arrays by stars (descending)
usort($owned, function($a, $b) {
return $b['stargazers_count'] <=> $a['stargazers_count'];
});
usort($contributed, function($a, $b) {
return $b['stargazers_count'] <=> $a['stargazers_count'];
});
return [
'owned' => $owned,
'contributed' => $contributed
];
}
/**
* Check if repository should be hidden
*/
private function isHidden(string $repoName): bool {
// Check exact match
if (in_array($repoName, $this->hiddenProjects, true)) {
return true;
}
// Check if repo name contains hidden project name
foreach ($this->hiddenProjects as $hidden) {
if (empty($hidden)) continue;
if (stripos($repoName, $hidden) !== false) {
return true;
}
}
return false;
}
/**
* Fetch repositories owned by the user
*/
private function fetchOwnedRepositories(): array {
$repos = $this->makeRequest("{$this->apiUrl}/users/{$this->username}/repos?sort=stars&per_page=100&type=owner");
if (!$repos) {
return $this->getFallbackProjects();
}
return $this->processRepositories($repos, true);
}
/**
* Fetch repositories where user contributed (but doesn't own)
* Shows original repositories, not forks. If user forked it, shows fork link.
*/
private function fetchContributedRepositories(): array {
// Get user's events to find contributed repos
$events = $this->makeRequest("{$this->apiUrl}/users/{$this->username}/events/public?per_page=100");
if (!$events) {
return [];
}
$contributedRepos = [];
$seenIds = [];
foreach ($events as $event) {
// Look for PushEvents and PullRequestEvents
if (!in_array($event['type'] ?? '', ['PushEvent', 'PullRequestEvent'])) {
continue;
}
if (!isset($event['repo']['name'])) {
continue;
}
$repoFullName = $event['repo']['name'];
// Skip own repos (user is the owner)
if (str_starts_with($repoFullName, $this->username . '/')) {
continue;
}
// Fetch full repo details
$repoDetails = $this->makeRequest("{$this->apiUrl}/repos/{$repoFullName}");
if (!$repoDetails) {
continue;
}
$targetRepo = null;
$userForkUrl = null;
$isForkContribution = false;
// If this is a fork, get the original repository
if ($repoDetails['fork'] ?? false) {
$isForkContribution = true;
// Fetch fork details to get parent info
$forkDetails = $this->makeRequest("{$this->apiUrl}/repos/{$repoFullName}");
if ($forkDetails && isset($forkDetails['parent'])) {
$parentRepo = $forkDetails['parent'];
$targetRepo = $parentRepo;
// Check if user's fork is public
if (!($forkDetails['private'] ?? true)) {
$userForkUrl = $forkDetails['html_url'];
}
} else {
// Can't get parent, skip this
continue;
}
} else {
// Not a fork, use as-is
$targetRepo = $repoDetails;
// Check if user has a public fork of this repo
$userForkUrl = $this->findUserFork($targetRepo['full_name']);
}
if (!$targetRepo) {
continue;
}
// Skip if already seen (by original repo ID)
$originalId = $targetRepo['id'];
if (in_array($originalId, $seenIds)) {
continue;
}
// Skip if this would be in owned repos
if (str_starts_with($targetRepo['full_name'], $this->username . '/')) {
continue;
}
$seenIds[] = $originalId;
$processedRepo = $this->processContributedRepository($targetRepo, $userForkUrl, $isForkContribution);
if ($processedRepo !== null) {
$contributedRepos[] = $processedRepo;
}
}
return $contributedRepos;
}
/**
* Cached user forks to avoid multiple API calls
*/
private ?array $userForksCache = null;
/**
* Find if user has a public fork of a repository (uses cache)
*/
private function findUserFork(string $originalFullName): ?string {
// Load forks once and cache
if ($this->userForksCache === null) {
$this->userForksCache = [];
$userRepos = $this->makeRequest("{$this->apiUrl}/users/{$this->username}/repos?type=forks&per_page=30");
if ($userRepos) {
foreach ($userRepos as $repo) {
if (($repo['fork'] ?? false) && isset($repo['parent'])) {
$parentName = $repo['parent']['full_name'];
if (!($repo['private'] ?? true)) {
$this->userForksCache[$parentName] = $repo['html_url'];
}
}
}
}
}
return $this->userForksCache[$originalFullName] ?? null;
}
/**
* Process contributed repository with fork information
*/
private function processContributedRepository(array $repo, ?string $userForkUrl, bool $isForkContribution): ?array {
$name = $repo['name'];
$fullName = $repo['full_name'] ?? $repo['name'];
// Skip hidden projects
if ($this->isHidden($name)) {
return null;
}
// Skip repos with numeric-only names (like "1")
if (is_numeric($name)) {
return null;
}
// Fetch all languages for this repo
$languages = $this->fetchLanguages($repo['languages_url'] ?? null);
return [
'id' => $repo['id'],
'name' => $name,
'full_name' => $fullName,
'description' => $repo['description'] ?: 'No description available',
'language' => $repo['language'] ?? 'Unknown',
'languages' => $languages,
'stargazers_count' => $repo['stargazers_count'] ?? 0,
'html_url' => $repo['html_url'],
'homepage' => $repo['homepage'] ?? null,
'created_at' => $repo['created_at'],
'updated_at' => $repo['updated_at'],
'is_owned' => false,
'is_private' => $repo['private'] ?? false,
'is_fork_contribution' => $isForkContribution,
'user_fork_url' => $userForkUrl
];
}
/**
* Make HTTP request to GitHub API
*/
private function makeRequest(string $url): ?array {
$options = [
'http' => [
'method' => 'GET',
'header' => [
'User-Agent: Portfolio-Site/1.0',
'Accept: application/vnd.github.v3+json'
],
'timeout' => 10,
'follow_location' => true
],
'ssl' => [
'verify_peer' => true,
'verify_peer_name' => true
]
];
if ($this->token) {
$options['http']['header'][] = 'Authorization: Bearer ' . $this->token;
}
$context = stream_context_create($options);
$response = @file_get_contents($url, false, $context);
if ($response === false) {
return null;
}
$data = json_decode($response, true);
return is_array($data) ? $data : null;
}
/**
* Process multiple repositories
*/
private function processRepositories(array $repos, bool $isOwned): array {
$processed = [];
foreach ($repos as $repo) {
// Skip forks in owned repos (we handle forks separately in contributed)
if ($repo['fork'] ?? false) {
continue;
}
$processedRepo = $this->processSingleRepository($repo, $isOwned);
if ($processedRepo !== null) {
$processed[] = $processedRepo;
}
}
return $processed;
}
/**
* Process single repository
*/
private function processSingleRepository(array $repo, bool $isOwned): ?array {
$name = $repo['name'];
$fullName = $repo['full_name'] ?? $repo['name'];
// Skip hidden projects
if ($this->isHidden($name)) {
return null;
}
// Skip repos with numeric-only names (like "1")
if (is_numeric($name)) {
return null;
}
// Fetch all languages for this repo
$languages = $this->fetchLanguages($repo['languages_url'] ?? null);
return [
'id' => $repo['id'],
'name' => $name,
'full_name' => $fullName,
'description' => $repo['description'] ?: 'No description available',
'language' => $repo['language'] ?? 'Unknown',
'languages' => $languages,
'stargazers_count' => $repo['stargazers_count'] ?? 0,
'html_url' => $repo['html_url'],
'homepage' => $repo['homepage'] ?? null,
'created_at' => $repo['created_at'],
'updated_at' => $repo['updated_at'],
'is_owned' => $isOwned,
'is_private' => $repo['private'] ?? false,
'is_fork_contribution' => false,
'user_fork_url' => null
];
}
/**
* Fetch all languages for a repository
*/
private function fetchLanguages(?string $languagesUrl): array {
if (!$languagesUrl) {
return [];
}
$languages = $this->makeRequest($languagesUrl);
if (!$languages || !is_array($languages)) {
return [];
}
// Return language names sorted by bytes (most used first)
arsort($languages);
return array_keys($languages);
}
/**
* Fallback projects in case API fails
*/
private function getFallbackProjects(): array {
return [
[
'id' => 1,
'name' => 'portfolio',
'full_name' => $this->username . '/portfolio',
'description' => 'My personal portfolio website with 3D effects',
'language' => 'PHP',
'stargazers_count' => 0,
'html_url' => 'https://github.com/' . $this->username . '/portfolio',
'homepage' => null,
'created_at' => date('Y-m-d'),
'updated_at' => date('Y-m-d'),
'is_owned' => true,
'is_private' => false,
'is_fork_contribution' => false,
'user_fork_url' => null
]
];
}
}