5 use App\Events\ParticipantChanged;
6 use Illuminate\Database\Eloquent\Factories\HasFactory;
7 use Illuminate\Database\Eloquent\Model;
9 class Participant extends Model
14 public static function compareResult(Round $round) {
15 return function (Participant $a, Participant $b) use ($round) {
16 $a_result = $a->findResult($round);
17 $b_result = $b->findResult($round);
18 $a_time = $a_result && !$a_result->forfeit ? $a_result->time : 0;
19 $b_time = $b_result && !$b_result->forfeit ? $b_result->time : 0;
22 if ($a_time < $b_time) return -1;
23 if ($b_time < $a_time) return 1;
24 return static::compareUsername($a, $b);
31 $a_forfeit = $a_result ? $a_result->forfeit : false;
32 $b_forfeit = $b_result ? $b_result->forfeit : false;
35 return static::compareUsername($a, $b);
42 return static::compareUsername($a, $b);
46 public static function compareScore(Participant $a, Participant $b) {
47 $a_score = $a->isRunner() ? ($a->score ? $a->score : 0) : -1;
48 $b_score = $b->isRunner() ? ($b->score ? $b->score : 0) : -1;
49 if ($a_score < $b_score) return -1;
50 if ($b_score < $a_score) return 1;
51 return static::compareUsername($a, $b);
54 public static function compareUsername(Participant $a, Participant $b) {
55 return strcasecmp($a->user->username, $b->user->username);
59 public function updatePlacement($score, $placement) {
60 $this->score = $score;
61 $this->placement = $placement;
63 if ($this->wasChanged()) {
64 ParticipantChanged::dispatch($this);
68 public function findResult(Round $round) {
69 foreach ($round->results as $result) {
70 if ($this->user_id == $result->user_id) {
77 public function isRunner() {
78 return in_array('runner', $this->roles);
81 public function isTournamentAdmin() {
82 return in_array('admin', $this->roles);
85 public function makeRunner() {
86 if (!is_array($this->roles)) {
87 $this->roles = ['runner'];
88 } else if (!in_array('runner', $this->roles)) {
89 $newRoles = array_values($this->roles);
90 $newRoles[] = 'runner';
91 $this->roles = $newRoles;
94 ParticipantChanged::dispatch($this);
98 public function tournament() {
99 return $this->belongsTo(Tournament::class);
102 public function user() {
103 return $this->belongsTo(User::class);
109 'user_id' => 'string',
112 protected $fillable = [