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
6namespace App\Models;
7
8/**
9 * @property Group $group
10 * @property int $group_id
11 * @property int $group_leader
12 * @property User $user
13 * @property int $user_id
14 * @property int $user_pending
15 * @property array|null $playmodes
16 */
17class UserGroup extends Model
18{
19 public $timestamps = false;
20 public $incrementing = false;
21
22 protected $casts = [
23 'user_pending' => 'boolean',
24 ];
25 protected $primaryKey = ':composite';
26 protected $primaryKeys = ['user_id', 'group_id'];
27 protected $table = 'phpbb_user_group';
28
29 public function group()
30 {
31 return $this->belongsTo(Group::class, 'group_id');
32 }
33
34 public function user()
35 {
36 return $this->belongsTo(User::class, 'user_id');
37 }
38
39 public function setPlaymodesAttribute(?array $value): void
40 {
41 $this->attributes['playmodes'] = $this->group->has_playmodes ? json_encode($value ?? []) : null;
42 }
43
44 public function actualRulesets(): array
45 {
46 static $defaultRulesets;
47 // sync with defaultGroupRulesets in resources/js/utils/beatmapset-discussion-helper.ts
48 $defaultRulesets ??= [
49 'nat' => array_keys(Beatmap::MODES),
50 ];
51
52 $visibleRulesets = $this->playmodes ?? [];
53
54 return $visibleRulesets === []
55 ? ($defaultRulesets[$this->group->identifier] ?? [])
56 : $visibleRulesets;
57 }
58
59 public function getAttribute($key)
60 {
61 return match ($key) {
62 'group_id',
63 'user_id' => $this->getRawAttribute($key),
64
65 'group_leader',
66 'user_pending' => (bool) $this->getRawAttribute($key),
67
68 'group' => app('groups')->byIdOrFail($this->group_id),
69 'playmodes' => $this->getPlaymodes(),
70
71 'user' => $this->getRelationValue($key),
72 };
73 }
74
75 private function getPlaymodes(): ?array
76 {
77 if ($this->group->has_playmodes) {
78 $value = $this->getRawAttribute('playmodes');
79
80 return $value === null ? [] : json_decode($value, true);
81 }
82
83 return null;
84 }
85}