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\Libraries;
7
8use App\Models\User;
9use App\Traits\Validatable;
10
11class ChangeUsername
12{
13 use Validatable;
14
15 const LESS_VALIDATION_TYPES = ['admin', 'revert', 'support'];
16
17 protected $type;
18
19 /** @var User */
20 protected $user;
21
22 protected $username;
23
24 public static function requireSupportedMessage()
25 {
26 $link = link_to(
27 route('support-the-game'),
28 osu_trans('model_validation.user.change_username.supporter_required.link_text')
29 );
30
31 return osu_trans('model_validation.user.change_username.supporter_required._', ['link' => $link]);
32 }
33
34 public function __construct(User $user, string $newUsername, string $type = 'paid')
35 {
36 $this->type = $type;
37 $this->username = $newUsername;
38 $this->user = $user;
39 }
40
41 public function validate(): ValidationErrors
42 {
43 $this->validationErrors()->reset();
44 if ($this->user->user_id <= 1) {
45 return $this->validationErrors()->addTranslated('user_id', 'This user cannot be renamed');
46 }
47
48 if ($this->hasExtraValidations() && $this->user->isRestricted()) {
49 return $this->validationErrors()->add('username', '.change_username.restricted');
50 }
51
52 if ($this->hasExtraValidations() && !$this->user->hasSupported()) {
53 return $this->validationErrors()->addTranslated('username', static::requireSupportedMessage());
54 }
55
56 if (User::cleanUsername($this->username) === $this->user->username_clean) {
57 return $this->validationErrors()->add('username', '.change_username.username_is_same');
58 }
59
60 if ($this->validationErrors()->merge(UsernameValidation::validateUsername($this->username))->isAny()) {
61 return $this->validationErrors();
62 }
63
64 if ($this->validationErrors()->merge(UsernameValidation::validateUsersOfUsername($this->username))->isAny()) {
65 return $this->validationErrors();
66 }
67
68 return $this->validationErrors()->merge(UsernameValidation::validateAvailability($this->username));
69 }
70
71 public function validationErrorsTranslationPrefix(): string
72 {
73 return 'user';
74 }
75
76 private function hasExtraValidations()
77 {
78 return !in_array($this->type, static::LESS_VALIDATION_TYPES, true);
79 }
80}