1<?php
2
3// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
4// See the LICENCE file in the repository root for full licence text.
5
6declare(strict_types=1);
7
8namespace App\Models;
9
10use Illuminate\Database\Eloquent\Relations\BelongsTo;
11use Illuminate\Database\Eloquent\Relations\HasMany;
12
13/**
14 * Note: `$canonical_id`, `$id`, and `$username` are null when this model is
15 * created for use in legacy changelog entries.
16 *
17 * @property int $canonical_id
18 * @property-read \Illuminate\Database\Eloquent\Collection<ChangelogEntry> $changelogEntries
19 * @property \Carbon\Carbon|null $created_at
20 * @property-read string|null $created_at_json
21 * @property int $id
22 * @property \Carbon\Carbon|null $updated_at
23 * @property-read string|null $updated_at_json
24 * @property-read User|null $user
25 * @property int|null $user_id
26 * @property string $username
27 */
28class GithubUser extends Model
29{
30 /**
31 * Check if the app is capable of authenticating users via the GitHub API.
32 */
33 public static function canAuthenticate(): bool
34 {
35 return $GLOBALS['cfg']['osu']['github']['client_id'] !== null
36 && $GLOBALS['cfg']['osu']['github']['client_secret'] !== null;
37 }
38
39 /**
40 * Create or update a GitHub user with data from the GitHub API.
41 */
42 public static function importFromGithub(array $apiUser): static
43 {
44 return static::updateOrCreate(
45 ['canonical_id' => $apiUser['id']],
46 [
47 'canonical_id' => $apiUser['id'],
48 'username' => $apiUser['login'],
49 ],
50 );
51 }
52
53 public function changelogEntries(): HasMany
54 {
55 return $this->hasMany(ChangelogEntry::class);
56 }
57
58 public function user(): BelongsTo
59 {
60 return $this->belongsTo(User::class, 'user_id');
61 }
62
63 public function displayUsername(): string
64 {
65 return $this->username ?? $this->user?->username ?? '[no name]';
66 }
67
68 public function githubUrl(): ?string
69 {
70 return $this->username !== null
71 ? "https://github.com/{$this->username}"
72 : null;
73 }
74
75 public function getAttribute($key)
76 {
77 return match ($key) {
78 'canonical_id',
79 'id',
80 'user_id',
81 'username' => $this->getRawAttribute($key),
82
83 'created_at',
84 'updated_at' => $this->getTimeFast($key),
85
86 'created_at_json',
87 'updated_at_json' => $this->getJsonTimeFast($key),
88
89 'changelogEntries',
90 'user' => $this->getRelationValue($key),
91 };
92 }
93}