Completed
Pull Request — master (#161)
by Vladimir
16:20 queued 13:30
created

Match::getName()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 32
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 32
ccs 15
cts 15
cp 1
rs 8.439
c 0
b 0
f 0
cc 6
eloc 21
nc 5
nop 0
crap 6
1
<?php
2
/**
3
 * This file contains functionality relating to the official matches played in the league
4
 *
5
 * @package    BZiON\Models
6
 * @license    https://github.com/allejo/bzion/blob/master/LICENSE.md GNU General Public License Version 3
7
 */
8
use BZIon\Model\Column\Timestamp;
9
10
/**
11
 * A match played between two teams
12
 * @package    BZiON\Models
13
 */
14
class Match extends UrlModel implements NamedModel
15
{
16
    const OFFICIAL = "official";
17
    const SPECIAL  = "special";
18
    const FUN      = "fm";
19
20
    const TEAM_V_TEAM   = 0;
21
    const TEAM_V_MIXED  = 1;
22
    const MIXED_V_MIXED = 2;
23
24
    use Timestamp;
25
26
    /**
27
     * The ID of the first team of the match
28
     * @var int
29
     */
30
    protected $team_a;
31
32
    /**
33
     * The ID of the second team of the match
34
     * @var int
35
     */
36
    protected $team_b;
37
38
    /**
39
     * The color of the first team
40
     * @var string
41
     */
42
    protected $team_a_color;
43
44
    /**
45
     * The color of the second team
46
     * @var string
47
     */
48
    protected $team_b_color;
49
50
    /**
51
     * The match points (usually the number of flag captures) Team A scored
52
     * @var int
53
     */
54
    protected $team_a_points;
55
56
    /**
57
     * The match points Team B scored
58
     * @var int
59
     */
60
    protected $team_b_points;
61
62
    /**
63
     * The callsigns players used during this match.
64
     * @var string[]
65
     */
66
    protected $player_callsigns;
67
68
    /**
69
     * An associative array of IP addresses used by players during this match.
70
     * @var string[]
71
     */
72
    protected $player_ip_addresses;
73
74
    /**
75
     * The players who participated in Team A during this match.
76
     * @var Player[]
77
     */
78
    protected $team_a_players;
79
80
    /**
81
     * The players who participated in Team B during this match.
82
     * @var Player[]
83
     */
84
    protected $team_b_players;
85
86
    /**
87
     * The ELO score of Team A after the match
88
     * @var int
89
     */
90
    protected $team_a_elo_new;
91
92
    /**
93
     * The ELO score of Team B after the match
94
     * @var int
95
     */
96
    protected $team_b_elo_new;
97
98
    /**
99
     * The map ID used in the match if the league supports more than one map
100
     * @var int
101
     */
102
    protected $map;
103
104
    /**
105
     * The type of match that occurred. Valid options: official, fm, special
106
     *
107
     * @var string
108
     */
109
    protected $match_type;
110
111
    /**
112
     * A JSON string of events that happened during a match, such as captures and substitutions
113
     * @var string
114
     */
115
    protected $match_details;
116
117
    /**
118
     * The ID of the server where this match took place
119
     * @var int
120
     */
121
    protected $server;
122
123
    /**
124
     * The server location of there the match took place
125
     * @var string
126
     */
127
    protected $server_address;
128
129
    /**
130
     * The file name of the replay file of the match
131
     * @var string
132
     */
133
    protected $replay_file;
134
135
    /**
136
     * The value of the ELO score difference
137
     * @var int
138
     */
139
    protected $elo_diff;
140
141
    /**
142
     * The value of the player Elo difference
143
     * @var int
144
     */
145
    protected $player_elo_diff;
146
147
    /**
148
     * @var array
149
     */
150
    protected $player_elo_changelog;
151
152
    /**
153
     * The timestamp representing when the match information was last updated
154
     * @var TimeDate
155
     */
156
    protected $updated;
157
158
    /**
159
     * The duration of the match in minutes
160
     * @var int
161
     */
162
    protected $duration;
163
164
    /**
165
     * The ID of the person (i.e. referee) who last updated the match information
166
     * @var string
167
     */
168
    protected $entered_by;
169
170
    const DEFAULT_STATUS = 'entered';
171 42
172
    /**
173 42
     * The name of the database table used for queries
174 42
     */
175 42
    const TABLE = "matches";
176 42
177 42
    const CREATE_PERMISSION = Permission::ENTER_MATCH;
178 42
    const EDIT_PERMISSION = Permission::EDIT_MATCH;
179 42
    const SOFT_DELETE_PERMISSION = Permission::SOFT_DELETE_MATCH;
180 42
    const HARD_DELETE_PERMISSION = Permission::HARD_DELETE_MATCH;
181 42
182 42
    /**
183 42
     * {@inheritdoc}
184 42
     */
185 42
    protected function assignResult($match)
186 42
    {
187 42
        $this->team_a = $match['team_a'];
188 42
        $this->team_b = $match['team_b'];
189 42
        $this->team_a_color = $match['team_a_color'];
190 42
        $this->team_b_color = $match['team_b_color'];
191 42
        $this->team_a_points = $match['team_a_points'];
192 42
        $this->team_b_points = $match['team_b_points'];
193 42
        $this->team_a_elo_new = $match['team_a_elo_new'];
194 42
        $this->team_b_elo_new = $match['team_b_elo_new'];
195 42
        $this->map = $match['map'];
196
        $this->match_type = $match['match_type'];
197
        $this->match_details = $match['match_details'];
198
        $this->server_address = $match['server'];
199
        $this->replay_file = $match['replay_file'];
200
        $this->elo_diff = $match['elo_diff'];
201
        $this->player_elo_diff = $match['player_elo_diff'];
202 1
        $this->timestamp = TimeDate::fromMysql($match['timestamp']);
203
        $this->updated = TimeDate::fromMysql($match['updated']);
204 1
        $this->duration = $match['duration'];
205
        $this->entered_by = $match['entered_by'];
206
        $this->status = $match['status'];
207
208
        // For legacy support (e.g. Phinx migrations) we need to check if the key exists. Prior to migrations, it didn't
209
        // exist so Phinx migrations prior to 20170912201127_match_server_relationship will throw warnings.
210
        //
211
        // @todo Look for a better solution
212
        $this->server = isset($match['server_id']) ? $match['server_id'] : null;
213
    }
214 1
215
    /**
216 1
     * Get the name of the route that shows the object
217 1
     * @param  string $action The route's suffix
218 1
     * @return string
219 1
     */
220
    public static function getRouteName($action = 'show')
221
    {
222 1
        return "match_$action";
223
    }
224
225
    /**
226
     * Get a one word description of a match relative to a team (i.e. win, loss, or draw)
227
     *
228
     * @param int|string|TeamInterface $teamID The team ID we want the noun for
229
     *
230
     * @return string Either "win", "loss", or "draw" relative to the team
231
     */
232 1
    public function getMatchDescription($teamID)
233
    {
234 1
        if ($this->getScore($teamID) > $this->getOpponentScore($teamID)) {
235
            return "win";
236
        } elseif ($this->getScore($teamID) < $this->getOpponentScore($teamID)) {
237
            return "loss";
238
        }
239
240
        return "tie";
241
    }
242
243
    /**
244 23
     * Get a one letter description of a match relative to a team (i.e. W, L, or T)
245
     *
246 23
     * @param int|string|TeamInterface $teamID The team ID we want the noun for
247
     *
248 23
     * @return string Either "W", "L", or "T" relative to the team
249 2
     */
250
    public function getMatchLetter($teamID)
251
    {
252
        return strtoupper(substr($this->getMatchDescription($teamID), 0, 1));
253
    }
254 23
255 23
    /**
256
     * Get the score of a specific team
257
     *
258 23
     * @param int|string|TeamInterface $teamID The team we want the score for
259
     *
260
     * @return int The score that team received
261
     */
262 View Code Duplication
    public function getScore($teamID)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
263
    {
264
        if ($teamID instanceof TeamInterface) {
265
            // Oh no! The caller gave us a Team model instead of an ID!
266
            $teamID = $teamID->getId();
267
        } elseif (is_string($teamID)) {
268 2
            // Make sure we're comparing lowercase strings
269
            $teamID = strtolower($teamID);
270 2
        }
271
272
        if ($this->getTeamA()->getId() == $teamID) {
273
            return $this->getTeamAPoints();
274
        }
275
276
        return $this->getTeamBPoints();
277
    }
278
279
    /**
280 36
     * Get the score of the opponent relative to a team
281
     *
282 36
     * @param int|string|TeamInterface $teamID The opponent of the team we want the score for
283 36
     *
284 2
     * @return int The score of the opponent
285
     */
286
    public function getOpponentScore($teamID)
287
    {
288 36
        return $this->getScore($this->getOpponent($teamID));
289 24
    }
290
291
    /**
292 14
     * Get the opponent of a match relative to a team ID
293
     *
294
     * @param int|string|TeamInterface $teamID The team who is known in a match
295
     *
296
     * @return TeamInterface The opponent team
297
     */
298 View Code Duplication
    public function getOpponent($teamID)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
299
    {
300 1
        if ($teamID instanceof TeamInterface) {
301
            $teamID = $teamID->getId();
302 1
        } elseif (is_string($teamID)) {
303
            $teamID = strtolower($teamID);
304
        }
305
306
        if ($this->getTeamA()->getId() == $teamID) {
307
            return $this->getTeamB();
308
        }
309
310
        return $this->getTeamA();
311
    }
312
313
    /**
314
     * Get the timestamp of the last update of the match
315
     *
316
     * @return TimeDate The match's update timestamp
317
     */
318
    public function getUpdated()
319
    {
320
        return $this->updated->copy();
321
    }
322 41
323
    /**
324 41
     * Set the timestamp of the match
325
     *
326 41
     * @param  mixed $timestamp The match's new timestamp
327 29
     * @return $this
328
     */
329
    public function setTimestamp($timestamp)
330 13
    {
331
        $this->updateProperty($this->timestamp, "timestamp", TimeDate::from($timestamp));
332
333
        return $this;
334
    }
335
336
    /**
337 41
     * Get the first team involved in the match
338
     * @return TeamInterface Team A
339 41
     */
340
    public function getTeamA()
341 41
    {
342 27
        $team = Team::get($this->team_a);
343
344
        if ($this->match_type === self::OFFICIAL && $team->isValid()) {
345 15
            return $team;
346
        }
347
348
        return new ColorTeam($this->team_a_color);
349
    }
350
351
    /**
352
     * Get the second team involved in the match
353
     * @return TeamInterface Team B
354
     */
355
    public function getTeamB()
356
    {
357
        $team = Team::get($this->team_b);
358
359
        if ($this->match_type === self::OFFICIAL && $team->isValid()) {
360
            return $team;
361
        }
362
363
        return new ColorTeam($this->team_b_color);
364
    }
365
366
    /**
367
     * Get the color of Team A
368
     * @return string
369
     */
370 39
    public function getTeamAColor()
371
    {
372 39
        return $this->team_a_color;
373
    }
374
375
    /**
376
     * Get the color of Team B
377
     * @return string
378
     */
379 39
    public function getTeamBColor()
380
    {
381 39
        return $this->team_b_color;
382
    }
383
384
    /**
385
     * Get the IP address a player used during this match.
386
     *
387
     * @param Player|int $id
388
     *
389 4
     * @return string|null
390
     */
391 4
    public function getPlayerIpAddress($id)
392 1
    {
393
        $this->lazyLoadMatchParticipants();
394
395 4
        if ($id instanceof Player) {
396 1
            $id = $id->getId();
397 4
        }
398 1
399
        return __::get($this->player_ip_addresses, $id, null);
400
    }
401 3
402
    /**
403
     * Get the callsign a player used during this match.
404
     *
405
     * @param Player|int $id
406
     *
407
     * @return string|null
408
     */
409
    public function getPlayerCallsign($id)
410
    {
411
        $this->lazyLoadMatchParticipants();
412
413
        if ($id instanceof Player) {
414
            $id = $id->getId();
415
        }
416
417
        return __::get($this->player_callsigns, $id, null);
418
    }
419
420
    /**
421
     * Get the list of players on Team A who participated in this match
422
     * @return Player[] Returns null if there were no players recorded for this match
423
     */
424 39
    public function getTeamAPlayers()
425
    {
426 39
        $this->lazyLoadMatchParticipants();
427 12
428
        return $this->team_a_players;
429
    }
430 30
431
    /**
432
     * Get the list of players on Team B who participated in this match
433
     * @return Player[] Returns null if there were no players recorded for this match
434
     */
435
    public function getTeamBPlayers()
436
    {
437 28
        $this->lazyLoadMatchParticipants();
438
439 28
        return $this->team_b_players;
440
    }
441
442
    /**
443
     * Get the list of players for a team in a match
444
     * @param  Team|int|null The team or team ID
445
     * @return Player[]|null Returns null if there were no players recorded for this match
446 28
     */
447
    public function getPlayers($team = null)
448 28
    {
449
        if ($team instanceof TeamInterface) {
450
            $team = $team->getId();
451
        }
452
453
        if ($this->getTeamA()->isValid() && $team === $this->getTeamA()->getId()) {
454
            return $this->getTeamAPlayers();
455
        } elseif ($this->getTeamB()->isValid() && $team === $this->getTeamB()->getId()) {
456
            return $this->getTeamBPlayers();
457
        }
458 1
459
        return array_merge($this->getTeamAPlayers(), $this->getTeamBPlayers());
460 1
    }
461 1
462
    /**
463 1
     * Set the players of the match's teams
464
     *
465
     * @param int[] $teamAPlayers An array of player IDs
466
     * @param int[] $teamBPlayers An array of player IDs
467
     * @return self
468
     */
469
    public function setTeamPlayers($teamAPlayers = [], $teamBPlayers = [], $teamAIPs = [], $teamBIPs = [], $teamACallsigns = [], $teamBCallsigns = [])
470
    {
471
        $this->db->execute('DELETE FROM match_participation WHERE match_id = ?', [
472
            $this->getId(),
473
        ]);
474
475
        $matchParticipation = [];
476
477
        $this->matchParticipationEntryBuilder(
478
            $matchParticipation,
479
            ($this->getTeamA() instanceof Team) ? $this->team_a : null,
480
            0,
481
            $teamAPlayers,
482
            $teamAIPs,
483
            $teamACallsigns
484
        );
485
        $this->matchParticipationEntryBuilder(
486
            $matchParticipation,
487
            ($this->getTeamB() instanceof Team) ? $this->team_b : null,
488
            1,
489
            $teamBPlayers,
490
            $teamBIPs,
491
            $teamBCallsigns
492
        );
493
494
        $this->db->insertBatch('match_participation', $matchParticipation);
495
496
        return $this;
497 30
    }
498
499 30
    /**
500
     * Load player participation in this match from its respective tables.
501
     */
502
    private function lazyLoadMatchParticipants()
503
    {
504
        if ($this->team_a_players !== null || $this->team_b_players !== null) {
505
            return;
506
        }
507
508
        $participation = $this->db->query('SELECT * FROM match_participation WHERE match_id = ?', [
509 39
            $this->getId(),
510
        ]);
511 39
512
        $loyalty = __::groupBy($participation, 'team_loyalty');
513
514
        $this->team_a_players = Player::arrayIdToModel(array_column(__::get($loyalty, 0, []), 'user_id'));
0 ignored issues
show
Documentation Bug introduced by
It seems like \Player::arrayIdToModel(..., array()), 'user_id')) of type array<integer,object<Model>> is incompatible with the declared type array<integer,object<Player>> of property $team_a_players.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
515
        $this->team_b_players = Player::arrayIdToModel(array_column(__::get($loyalty, 1, []), 'user_id'));
0 ignored issues
show
Documentation Bug introduced by
It seems like \Player::arrayIdToModel(..., array()), 'user_id')) of type array<integer,object<Model>> is incompatible with the declared type array<integer,object<Player>> of property $team_b_players.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
516
517 1
        $this->player_callsigns = array_column($participation, 'callsign', 'user_id');
518
        $this->player_ip_addresses = array_column($participation, 'ip_address', 'user_id');
519 1
    }
520 1
521
    /**
522
     * Get the first team's points
523 1
     * @return int Team A's points
524
     */
525 1
    public function getTeamAPoints()
526 1
    {
527 1
        return $this->team_a_points;
528 1
    }
529
530
    /**
531 1
     * Get the second team's points
532
     * @return int Team B's points
533
     */
534
    public function getTeamBPoints()
535
    {
536
        return $this->team_b_points;
537
    }
538
539
    /**
540 1
     * Set the match team points
541
     *
542 1
     * @param  int $teamAPoints Team A's points
543
     * @param  int $teamBPoints Team B's points
544 1
     * @return self
545 1
     */
546
    public function setTeamPoints($teamAPoints, $teamBPoints)
547
    {
548 1
        $this->updateProperty($this->team_a_points, "team_a_points", $teamAPoints);
549
        $this->updateProperty($this->team_b_points, "team_b_points", $teamBPoints);
550
551
        return $this;
552
    }
553
554
    /**
555
     * Set the match team colors
556
     *
557
     * @param  ColorTeam|string $teamAColor The color of team A
558 1
     * @param  ColorTeam|string $teamBColor The color of team B
559
     * @return self
560 1
     */
561
    public function setTeamColors($teamAColor, $teamBColor)
562 1
    {
563 1
        if ($this->isOfficial()) {
564
            throw new \Exception("Cannot change team colors in an official match");
565
        }
566 1
567
        if ($teamAColor instanceof ColorTeam) {
568
            $teamAColor = $teamAColor->getId();
569
        }
570
        if ($teamBColor instanceof ColorTeam) {
571
            $teamBColor = $teamBColor->getId();
572
        }
573
574
        $this->updateProperty($this->team_a_color, "team_a_color", $teamAColor);
575
        $this->updateProperty($this->team_b_color, "team_b_color", $teamBColor);
576
    }
577
578
    /**
579
     * Get the ELO difference applied to each team's old ELO
580
     *
581
     * @param bool $absoluteValue Whether or not to get the absolute value of the Elo difference
582
     *
583 7
     * @return int The ELO difference
584
     */
585 7
    public function getEloDiff($absoluteValue = true)
586
    {
587
        return ($absoluteValue) ? abs($this->elo_diff) : $this->elo_diff;
588
    }
589
590
    /**
591
     * Get the Elo difference applied to players
592 7
     *
593
     * @param bool $absoluteValue Whether or not to get the absolute value of the Elo difference
594 7
     *
595
     * @return int The Elo difference for players
596
     */
597
    public function getPlayerEloDiff($absoluteValue = true)
598
    {
599
        return ($absoluteValue && $this->player_elo_diff !== null) ? abs($this->player_elo_diff) : $this->player_elo_diff;
600
    }
601 7
602
    /**
603 7
     * Get the changelog for the player Elos for this match and cache them
604
     */
605
    private function getPlayerEloChangelog()
606
    {
607
        if ($this->player_elo_changelog !== null) {
608
            return;
609
        }
610 7
611
        $results = $this->db->query('SELECT * FROM player_elo WHERE match_id = ?', $this->getId());
612 7
613
        foreach ($results as $result) {
614
            $this->player_elo_changelog[$result['user_id']] = [
615
                'before' => $result['elo_previous'],
616
                'after'  => $result['elo_new']
617
            ];
618
        }
619
    }
620
621 1
    /**
622
     * Get the Elo for the player before this match occurred
623 1
     *
624 1
     * @param Player $player
625 1
     *
626 1
     * @return null|int
627
     */
628 View Code Duplication
    public function getPlayerEloBefore(Player $player)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
629
    {
630
        $this->getPlayerEloChangelog();
631
632
        if (isset($this->player_elo_changelog[$player->getId()])) {
633
            return $this->player_elo_changelog[$player->getId()]['before'];
634
        }
635
636
        return null;
637
    }
638 1
639
    /**
640 1
     * Get the Elo for the player after this match occurred
641 1
     *
642 1
     * @param Player $player
643 1
     *
644
     * @return null|int
645
     */
646 View Code Duplication
    public function getPlayerEloAfter(Player $player)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
647
    {
648
        $this->getPlayerEloChangelog();
649
650
        if (isset($this->player_elo_changelog[$player->getId()])) {
651
            return $this->player_elo_changelog[$player->getId()]['after'];
652
        }
653 1
654
        return null;
655 1
    }
656
657
    /**
658
     * Set the Elo difference applied to players
659
     *
660
     * @param int $diff
661
     */
662
    public function setPlayerEloDiff($diff)
663
    {
664
        $this->updateProperty($this->player_elo_diff, 'player_elo_diff', $diff);
665
    }
666
667
    /**
668
     * Get the first team's new ELO
669
     * @return int Team A's new ELO
670
     */
671
    public function getTeamAEloNew()
672
    {
673
        return $this->team_a_elo_new;
674
    }
675
676
    /**
677
     * Get the second team's new ELO
678
     * @return int Team B's new ELO
679
     */
680
    public function getTeamBEloNew()
681
    {
682 23
        return $this->team_b_elo_new;
683
    }
684 23
685 9
    /**
686 14
     * Get the first team's old ELO
687 9
     * @return int
688
     */
689
    public function getTeamAEloOld()
690 5
    {
691
        return $this->team_a_elo_new - $this->elo_diff;
692
    }
693
694
    /**
695
     * Get the second team's old ELO
696
     * @return int
697
     */
698 23
    public function getTeamBEloOld()
699
    {
700 23
        return $this->team_b_elo_new + $this->elo_diff;
701
    }
702
703
    /**
704
     * Get the team's new ELO
705
     * @param  Team $team The team whose new ELO to return
706
     * @return int|null   The new ELO, or null if the team provided has not
707
     *                    participated in the match
708
     */
709
    public function getTeamEloNew(Team $team)
710
    {
711
        if ($team->getId() == $this->team_a) {
712
            return $this->getTeamAEloNew();
713
        } elseif ($team->getId() == $this->team_b) {
714
            return $this->getTeamBEloNew();
715
        }
716
717
        return null;
718
    }
719
720
    /**
721
     * Get the team's old ELO
722
     * @param  Team $team The team whose old ELO to return
723
     * @return int|null   The old ELO, or null if the team provided has not
724
     *                    participated in the match
725
     */
726
    public function getTeamEloOld(Team $team)
727
    {
728 1
        if ($team->getId() == $this->team_a) {
729
            return $this->getTeamAEloOld();
730 1
        } elseif ($team->getId() == $this->team_b) {
731
            return $this->getTeamBEloOld();
732
        }
733
734
        return null;
735
    }
736
737
    /**
738
     * Get the map where the match was played on
739
     * @return Map Returns an invalid map if no map was found
740
     */
741
    public function getMap()
742
    {
743
        return Map::get($this->map);
744
    }
745
746
    /**
747
     * Set the map where the match was played
748
     * @param  int $map The ID of the map
749
     * @return self
750
     */
751
    public function setMap($map)
752 1
    {
753
        $this->updateProperty($this->map, "map", $map, "s");
754 1
755
        return $this;
756
    }
757
758 1
    /**
759
     * Get the type of official match this is. Whether it has just traditional teams or has mixed teams.
760
     *
761
     * Possible official match types:
762
     *   - Team vs Team
763
     *   - Team vs Mixed
764
     *   - Mixed vs Mixed
765 6
     *
766
     * @see Match::TEAM_V_TEAM
767 6
     * @see Match::TEAM_V_MIXED
768
     * @see Match::MIXED_V_MIXED
769
     *
770
     * @return int
771
     */
772
    public function getTeamMatchType()
773
    {
774
        if ($this->getTeamA()->supportsMatchCount() && $this->getTeamB()->supportsMatchCount()) {
775
            return self::TEAM_V_TEAM;
776
        } elseif ($this->getTeamA()->supportsMatchCount() xor $this->getTeamB()->supportsMatchCount()) {
777
            return self::TEAM_V_MIXED;
778
        }
779
780
        return self::MIXED_V_MIXED;
781
    }
782
783
    /**
784
     * Get the match type
785 2
     *
786
     * @return string 'official', 'fm', or 'special'
787 2
     */
788
    public function getMatchType()
789
    {
790
        return $this->match_type;
791
    }
792
793
    /**
794
     * Set the match type
795 36
     *
796
     * @param  string $matchType A valid match type; official, fm, special
797
     *
798 36
     * @return static
799
     */
800
    public function setMatchType($matchType)
801 36
    {
802
        return $this->updateProperty($this->match_type, "match_type", $matchType, 's');
803
    }
804
805
    /**
806
     * Get a JSON decoded array of events that occurred during the match
807
     * @return mixed|null Returns null if there were no events recorded for the match
808
     */
809 36
    public function getMatchDetails()
810
    {
811
        return json_decode($this->match_details);
812
    }
813
814
    /**
815 36
     * Get the server this match took place on
816 22
     *
817 15
     * @return Server
818 12
     */
819 3
    public function getServer()
820
    {
821 2
        return Server::get($this->server);
822 1
    }
823
824
    /**
825
     * Set the server this match took place on
826
     *
827 1
     * @param  int $serverID
828
     *
829
     * @return $this
830
     */
831
    public function setServer($serverID = null)
832
    {
833
        $this->updateProperty($this->server, 'server_id', $serverID);
834 39
835
        return $this;
836 39
    }
837
838
    /**
839
     * Get the server address of the server where this match took place
840
     *
841
     * @deprecated 0.10.0 Use Match::getServer() instead. Using this function is reserved for migrations/legacy support.
842
     *
843
     * @see 20170912201127_match_server_relationship.php
844
     *
845 1
     * @return string|null Returns null if there was no server address recorded
846
     */
847 1
    public function getServerAddress()
848
    {
849
        return $this->server_address;
850
    }
851
852
    /**
853 22
     * Get the name of the replay file for this specific map
854
     * @param  int    $length The length of the replay file name; it will be truncated
855 22
     * @return string Returns null if there was no replay file name recorded
856
     */
857
    public function getReplayFileName($length = 0)
858
    {
859
        if ($length > 0) {
860
            return substr($this->replay_file, 0, $length);
861
        }
862
863
        return $this->replay_file;
864
    }
865
866
    /**
867
     * Get the match duration
868
     * @return int The duration of the match in minutes
869
     */
870
    public function getDuration()
871
    {
872
        return $this->duration;
873
    }
874
875
    /**
876
     * Set the match duration
877
     *
878 1
     * @param  int  $duration The new duration of the match in minutes
879
     * @return self
880 1
     */
881 1
    public function setDuration($duration)
882
    {
883 1
        return $this->updateProperty($this->duration, "duration", $duration);
884
    }
885 1
886
    /**
887
     * Get the user who entered the match
888
     * @return Player
889 1
     */
890
    public function getEnteredBy()
891
    {
892
        return Player::get($this->entered_by);
893
    }
894
895
    /**
896
     * Get the loser of the match
897
     *
898
     * @return TeamInterface The team that was the loser or the team with the lower elo if the match was a draw
899
     */
900
    public function getLoser()
901
    {
902
        // Get the winner of the match
903
        $winner = $this->getWinner();
904
905
        // Get the team that wasn't the winner... Duh
906
        return $this->getOpponent($winner);
907 42
    }
908
909
    /**
910 42
     * Get the winner of a match
911
     *
912 42
     * @return TeamInterface The team that was the victor or the team with the lower elo if the match was a draw
913 23
     */
914 20
    public function getWinner()
915 14
    {
916
        // "As Mother Teresa once said, it's not enough if you win. Others must lose."
917
        //   -Stephen Colbert
918 42
919 42
        // Get the team that had its Elo increased or the team whose players had their Elo increased
920 3
        if ($this->elo_diff > 0 || $this->player_elo_diff > 0) {
921
            return $this->getTeamA();
922
        } elseif ($this->elo_diff < 0 || $this->player_elo_diff < 0) {
923
            return $this->getTeamB();
924
        } elseif ($this->team_a_points > $this->team_b_points) {
925
            // In case we're dealing with a match such an FM that doesn't have an ELO difference
926
            return $this->getTeamA();
927
        } elseif ($this->team_a_points < $this->team_b_points) {
928 39
            return $this->getTeamB();
929
        }
930 39
931 39
        // If the scores are the same, return Team A because well, fuck you that's why
932
        return $this->getTeamA();
933
    }
934 39
935 28
    /**
936 28
     * Determine whether the match was a draw
937
     * @return bool True if the match ended without any winning teams
938 28
     */
939
    public function isDraw()
940
    {
941
        return $this->team_a_points == $this->team_b_points;
942
    }
943
944
    /**
945
     * Find out whether the match involves a team
946 39
     *
947
     * @param  TeamInterface $team The team to check
948
     * @return bool
949
     */
950
    public function involvesTeam($team)
951 39
    {
952 23
        return $team->getId() == $this->getTeamA()->getId() || $team->getId() == $this->getTeamB()->getId();
953 17
    }
954 11
955 11
    /**
956
     * Find out if the match is played between official teams
957 11
     */
958
    public function isOfficial()
959
    {
960
        return self::OFFICIAL === $this->getMatchType();
961 39
    }
962 39
963 39
    /**
964
     * Reset the ELOs of the teams participating in the match
965
     *
966
     * @return self
967
     */
968
    public function resetTeamElos()
969
    {
970
        if ($this->match_type === self::OFFICIAL) {
971
            $this->getTeamA()->supportsMatchCount() && $this->getTeamA()->changeELO(-$this->elo_diff);
0 ignored issues
show
Bug introduced by
The method changeELO() does not seem to exist on object<TeamInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
972
            $this->getTeamB()->supportsMatchCount() && $this->getTeamB()->changeELO(+$this->elo_diff);
0 ignored issues
show
Bug introduced by
The method changeELO() does not seem to exist on object<TeamInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
973
        }
974
975
        return $this;
976
    }
977
978
    /**
979
     * Calculate the match's contribution to the team activity
980
     *
981
     * @return float
982
     */
983
    public function getActivity()
984
    {
985
        $daysPassed = $this->getTimestamp()->diffInSeconds();
986
        $daysPassed = $daysPassed / TimeDate::SECONDS_PER_MINUTE / TimeDate::MINUTES_PER_HOUR / TimeDate::HOURS_PER_DAY;
987
988
        $activity = 0.0116687059537612 * (pow(45 - $daysPassed, (1 / 6)) + atan(31.0 - $daysPassed) / 2.0);
989
990 45
        if (is_nan($activity) || $activity < 0.0) {
991
            return 0.0;
992
        }
993
994
        return $activity;
995
    }
996 45
997 45
    /**
998 45
     * Calculate the Elo differences for players and teams for a given match.
999 45
     *
1000 45
     * @param  Team $a
1001 45
     * @param  Team $b
1002 45
     * @param  int  $a_points
1003 45
     * @param  int  $b_points
1004 45
     * @param  int[]|Player[] $a_players
1005 45
     * @param  int[]|Player[] $b_players
1006 45
     * @param  int  $duration
1007 45
     *
1008 45
     * @throws InvalidArgumentException When a "Mixed" team is entered without a player roster
1009 45
     *
1010
     * @return array
1011
     */
1012
    private static function calculateElos($a, $b, $a_points, $b_points, $a_players, $b_players, $duration)
1013 45
    {
1014
        // Get the type of official match
1015 45
        $matchType = Match::MIXED_V_MIXED;
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
1016 42
1017 42
        if ($a->supportsMatchCount() && $b->supportsMatchCount()) {
1018
            $matchType = Match::TEAM_V_TEAM;
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
1019 42
        } elseif ($a->supportsMatchCount() xor $b->supportsMatchCount()) {
1020
            $matchType = Match::TEAM_V_MIXED;
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
1021 39
        }
1022 39
1023
        if ($matchType == Match::TEAM_V_MIXED &&
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
1024
            ((!$a->isValid() && empty($a_players)) || (!$b->isValid() && empty($b_players)))) {
1025 39
            throw new InvalidArgumentException('A Mixed team must have a player roster to calculate the Elo for team Elo differences');
1026 29
        }
1027
1028 29
        //
1029 29
        // Handle Player Elo Diff Calculations
1030
        //
1031 39
1032 27
        // By default, we won't have a player Elo difference since we won't force matches to have a roster
1033
        $playerEloDiff = null;
1034 27
1035 27
        $a_players_elo = 1200;
1036
        $b_players_elo = 1200;
1037
1038
        // Only bother to calculate a player Elo diff if we have players reported for both teams
1039 42
        if (!empty($a_players) && !empty($b_players)) {
1040 42
            $a_players_elo = self::getAveragePlayerElo($a_players);
1041 42
            $b_players_elo = self::getAveragePlayerElo($b_players);
1042
1043 42
            $playerEloDiff = self::calculateEloDiff($a_players_elo, $b_players_elo, $a_points, $b_points, $duration);
1044
        }
1045
1046
        //
1047
        // Handle Team Elo Diff Calculations
1048
        //
1049
1050
        // By default, we'll assume a Mixed vs Mixed official match where Elos do not change for teams
1051
        $teamEloDiff = null;
1052
1053
        // Work with calculations for team Elos to handle the following situations:
1054
        //   - Team vs Team  :: Use team Elos for calculations
1055
        //   - Team vs Mixed :: Use team Elo and the player average Elo for the "Mixed" team
1056
        if ($matchType == Match::TEAM_V_TEAM) {
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
1057
            $teamEloDiff = self::calculateEloDiff($a->getElo(), $b->getElo(), $a_points, $b_points, $duration);
1058
        } elseif ($matchType == Match::TEAM_V_MIXED) {
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
1059 39
            $a_team_elo = ($a->supportsMatchCount()) ? $a->getElo() : $a_players_elo;
1060
            $b_team_elo = ($b->supportsMatchCount()) ? $b->getElo() : $b_players_elo;
1061 39
1062 39
            $teamEloDiff = self::calculateEloDiff($a_team_elo, $b_team_elo, $a_points, $b_points, $duration);
1063 14
        }
1064 27
1065 19
        return [
1066
            'match_type' => $matchType,
1067 8
            'team_elo'   => $teamEloDiff,
1068
            'player_elo' => $playerEloDiff
1069
        ];
1070
    }
1071 39
1072 39
    /**
1073
     * Enter a new match to the database
1074 39
     * @param  int             $a          Team A's ID
1075
     * @param  int             $b          Team B's ID
1076 2
     * @param  int             $a_points   Team A's match points
1077
     * @param  int             $b_points   Team B's match points
1078
     * @param  int             $duration   The match duration in minutes
1079
     * @param  int|null        $entered_by The ID of the player reporting the match
1080 37
     * @param  string|DateTime $timestamp  When the match was played
1081
     * @param  int[]           $a_players  The IDs of the first team's players
1082
     * @param  int[]           $b_players  The IDs of the second team's players
1083
     * @param  string|null     $server     The address of the server where the match was played
1084
     * @param  string          $replayFile The name of the replay file of the match
1085
     * @param  int             $map        The ID of the map where the match was played, only for rotational leagues
1086
     * @param  string          $matchType  The type of match (e.g. official, fm, special)
1087
     * @param  string          $a_color    Team A's color
1088
     * @param  string          $b_color    Team b's color
1089
     * @param  string[]        $a_ipAddresses The IP addresses of players on Team A. The order of this array should
1090
     *                                        match the order of $a_players
1091
     * @param  string[]        $b_ipAddresses The IP addresses of players on Team B. The order of this array should
1092
     *                                        match the order of $b_players
1093
     * @param  string[]        $a_callsigns   The callsigns of players on Team A. The order of this array should match
1094
     *                                        the order of $a_players
1095
     * @param  string[]        $b_callsigns   The callsigns of players on Team B. The order of this array should match
1096
     *                                        the order of $b_players
1097
     *
1098
     * @throws \Exception               When no testing environment has been configured for the database.
1099
     * @throws InvalidArgumentException When a ColorTeam is selected for an official match and no players are defined
1100 3
     *                                  for that team
1101
     *
1102 3
     * @return Match           An object representing the match that was just entered
1103
     */
1104
    public static function enterMatch(
1105
        $a, $b, $a_points, $b_points, $duration, $entered_by, $timestamp = "now",
1106 3
        $a_players = array(), $b_players = array(), $server = null, $replayFile = null,
1107 3
        $map = null, $matchType = "official", $a_color = null, $b_color = null,
1108
        $a_ipAddresses = array(), $b_ipAddresses = array(), $a_callsigns = array(), $b_callsigns = array()
1109 3
    ) {
1110
        $matchData = array(
1111 3
            'team_a_color'   => strtolower($a_color),
1112 3
            'team_b_color'   => strtolower($b_color),
1113
            'team_a_points'  => $a_points,
1114
            'team_b_points'  => $b_points,
1115 3
            'timestamp'      => TimeDate::from($timestamp)->toMysql(),
1116 3
            'duration'       => $duration,
1117 3
            'entered_by'     => $entered_by,
1118 3
            'server'         => $server,
1119 3
            'replay_file'    => $replayFile,
1120
            'map'            => $map,
1121
            'status'         => 'entered',
1122 3
            'match_type'     => $matchType
1123
        );
1124 3
1125 3
        // (P)layer Elo Diff and (T)eam Elo Diff; respectively
1126
        $tEloDiff = null;
0 ignored issues
show
Unused Code introduced by
$tEloDiff is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1127 3
1128 3
        if ($matchType === self::OFFICIAL) {
1129 3
            $team_a = Team::get($a);
1130
            $team_b = Team::get($b);
1131
1132 3
            $eloCalcs = self::calculateElos($team_a, $team_b, $a_points, $b_points, $a_players, $b_players, $duration);
1133 3
1134 3
            $matchData['elo_diff'] = $tEloDiff = $eloCalcs['team_elo'];
1135
            $matchData['player_elo_diff'] = $eloCalcs['player_elo'];
1136
1137 3
            // Update team ELOs
1138 3
            if ($team_a->isValid()) {
1139
                $team_a->adjustElo($tEloDiff);
1140
1141
                $matchData['team_a'] = $a;
1142
                $matchData['team_a_elo_new'] = $team_a->getElo();
1143 1
            }
1144
            if ($team_b->isValid()) {
1145 1
                $team_b->adjustElo(-$tEloDiff);
1146
1147
                $matchData['team_b'] = $b;
1148
                $matchData['team_b_elo_new'] = $team_b->getElo();
1149
            }
1150
        }
1151
1152 26
        $match = self::create($matchData, 'updated');
1153
        $match->setTeamPlayers(
1154 26
            $a_players, $b_players,
1155 26
            $a_ipAddresses, $b_ipAddresses,
1156
            $a_callsigns, $b_callsigns
1157
        );
1158
        $match->updateMatchCount();
1159
        $match->updatePlayerElo();
1160
1161
        return $match;
1162
    }
1163
1164
    /**
1165
     * Calculate the ELO score difference
1166
     *
1167
     * Computes the ELO score difference on each team after a match, based on
1168
     * GU League's rules.
1169
     *
1170
     * @param  int $a_elo    Team A's current ELO score
1171 1
     * @param  int $b_elo    Team B's current ELO score
1172
     * @param  int $a_points Team A's match points
1173 1
     * @param  int $b_points Team B's match points
1174
     * @param  int $duration The match duration in minutes
1175 1
     * @return int The ELO score difference
1176 1
     */
1177
    public static function calculateEloDiff($a_elo, $b_elo, $a_points, $b_points, $duration)
1178
    {
1179
        $prob = 1.0 / (1 + pow(10, (($b_elo - $a_elo) / 400.0)));
1180
        if ($a_points > $b_points) {
1181 3
            $diff = 50 * (1 - $prob);
1182
        } elseif ($a_points == $b_points) {
1183 3
            $diff = 50 * (0.5 - $prob);
1184
        } else {
1185
            $diff = 50 * (0 - $prob);
1186
        }
1187
1188
        // Apply ELO modifiers from `config.yml`
1189 22
        $durations = Service::getParameter('bzion.league.duration');
1190
        $diff *= (isset($durations[$duration])) ? $durations[$duration] : 1;
1191 22
1192
        if (abs($diff) < 1 && $diff != 0) {
1193 22
            // ELOs such as 0.75 should round up to 1...
1194 22
            return ($diff > 0) ? 1 : -1;
1195
        }
1196 21
1197 9
        // ...everything else is rounded down (-3.7 becomes -3 and 48.1 becomes 48)
1198
        return intval($diff);
1199 21
    }
1200
1201 2
    /**
1202 2
     * Find if a match's stored ELO is correct
1203 2
     */
1204
    public function isEloCorrect()
1205
    {
1206
        return $this->elo_diff === $this->calculateEloDiff(
1207
            $this->getTeamAEloOld(),
1208
            $this->getTeamBEloOld(),
1209
            $this->getTeamAPoints(),
1210
            $this->getTeamBPoints(),
1211
            $this->getDuration()
1212
        );
1213 22
    }
1214 22
1215 22
    /**
1216 22
     * Remove Elo recordings for players participating in this match
1217 22
     */
1218 22
    public function resetPlayerElos()
1219
    {
1220
        $this->db->execute('DELETE FROM player_elo WHERE match_id = ?', [$this->getId()]);
1221
    }
1222
1223
    /**
1224
     * Recalculate the match's elo and adjust the team ELO values
1225
     */
1226
    public function recalculateElo()
1227
    {
1228
        if ($this->match_type !== self::OFFICIAL) {
1229
            return;
1230
        }
1231
1232
        $a = $this->getTeamA();
1233
        $b = $this->getTeamB();
1234
1235
        $this->resetPlayerElos();
1236
1237 1
        foreach ($this->getPlayers() as $player) {
0 ignored issues
show
Bug introduced by
The expression $this->getPlayers() of type array<integer,object<Player>>|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
1238
            $player->invalidateMatchFromCache($this);
1239
        }
1240
1241
        $eloCalcs = self::calculateElos(
1242
            $a, $b,
0 ignored issues
show
Compatibility introduced by
$a of type object<TeamInterface> is not a sub-type of object<Team>. It seems like you assume a concrete implementation of the interface TeamInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
Compatibility introduced by
$b of type object<TeamInterface> is not a sub-type of object<Team>. It seems like you assume a concrete implementation of the interface TeamInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
1243 1
            $this->getTeamAPoints(), $this->getTeamBPoints(),
1244 1
            $this->getTeamAPlayers(), $this->getTeamBPlayers(),
1245 1
            $this->getDuration()
1246 1
        );
1247 1
1248
        $elo = $eloCalcs['team_elo'];
1249
1250 1
        $this->updateProperty($this->elo_diff, 'elo_diff', $elo);
1251
        $this->updateProperty($this->player_elo_diff, 'player_elo_diff', $eloCalcs['player_elo']);
1252
1253 1
        if ($a->supportsMatchCount()) {
1254
            $a->adjustElo($elo);
1255
            $this->updateProperty($this->team_a_elo_new, 'team_a_elo_new', $a->getElo());
1256
        }
1257 1
1258
        if ($b->supportsMatchCount()) {
1259 1
            $b->adjustElo(-$elo);
1260
            $this->updateProperty($this->team_b_elo_new, 'team_b_elo_new', $b->getElo());
1261
        }
1262
1263 1
        $this->updatePlayerElo();
1264 1
    }
1265 1
1266
    /**
1267 1
     * Get all the matches in the database
1268 1
     */
1269 1
    public static function getMatches()
1270
    {
1271
        return self::getQueryBuilder()->active()->getModels();
1272 1
    }
1273
1274 1
    /**
1275
     * Get a query builder for matches
1276
     * @return MatchQueryBuilder
1277
     */
1278 1
    public static function getQueryBuilder()
1279
    {
1280
        return new MatchQueryBuilder('Match', array(
1281
            'columns' => array(
1282
                'firstTeam'        => 'team_a',
1283 1
                'secondTeam'       => 'team_b',
1284
                'firstTeamPoints'  => 'team_a_points',
1285
                'secondTeamPoints' => 'team_b_points',
1286
                'time'             => 'timestamp',
1287 1
                'map'              => 'map',
1288
                'server'           => 'server_id',
1289
                'type'             => 'match_type',
1290
                'status'           => 'status'
1291
            ),
1292
        ));
1293
    }
1294
1295 1
    /**
1296
     * {@inheritdoc}
1297 1
     */
1298 1
    public function delete()
1299
    {
1300
        $this->updateMatchCount(true);
1301
1302
        parent::delete();
1303
    }
1304
1305
    /**
1306
     * {@inheritdoc}
1307
     */
1308
    public function getName()
1309 28
    {
1310 28
        $description = '';
1311 2
1312
        switch ($this->getMatchType()) {
1313
            case self::OFFICIAL:
1314 28
                // Only show Elo diff if both teams are actual teams
1315 28
                if ($this->getTeamA()->supportsMatchCount() && $this->getTeamB()->supportsMatchCount()) {
1316
                    $description = "(+/- {$this->getEloDiff()})";
1317 28
                }
1318
                break;
1319
1320
            case self::FUN:
1321
                $description = 'Fun Match:';
1322
                break;
1323
1324
            case self::SPECIAL:
1325 42
                $description = 'Special Match:';
1326
                break;
1327 42
1328 4
            default:
1329
                break;
1330
        }
1331 39
1332
        return trim(sprintf('%s %s [%d] vs [%d] %s',
1333 39
            $description,
1334 19
            $this->getWinner()->getName(),
1335 19
            $this->getScore($this->getWinner()),
1336
            $this->getScore($this->getLoser()),
1337 21
            $this->getLoser()->getName()
1338 21
        ));
1339
    }
1340 39
1341
    /**
1342
     * Recalculates match history for all teams and matches
1343
     *
1344
     * Recalculation is done as follows:
1345 42
     * 1. A match is chosen as a starting point - it's stored old team ELOs are
1346
     *    considered correct
1347 42
     * 2. Team ELOs are reset to their values at the starting point
1348 4
     * 3. Each match that occurred since the first specified match has its ELO
1349
     *    recalculated based on the current team values, and the new match data
1350
     *    and team ELOs are stored in the database
1351 39
     *
1352
     * @param Match $match The first match
1353 39
     *
1354 28
     * @throws Exception
1355 28
     */
1356
    public static function recalculateMatchesSince(Match $match)
1357
    {
1358 39
        try {
1359 29
            // Commented out to prevent ridiculously large recalculations
1360 29
            //set_time_limit(0);
1361
1362 39
            $query = Match::getQueryBuilder()
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
1363
                ->where('status')->notEquals('deleted')
1364
                ->where('type')->equals(Match::OFFICIAL)
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
1365
                ->where('time')->isAfter($match->getTimestamp(), $inclusive = true)
1366
                ->sortBy('time');
1367
1368
            /** @var Match[] $matches */
1369
            $matches = $query->getModels($fast = true);
1370
1371
            // Send the total count to client-side javascript
1372
            echo count($matches) . "\n";
1373
1374
            // Start a transaction so tables are locked and we don't stay with
1375
            // messed up data if something goes wrong
1376
            Database::getInstance()->startTransaction();
1377
1378
            $teamsReset = [];
1379
1380
            // Reset match teams, in case the selected match is deleted and does
1381
            // not show up in the list of matches to recalculate
1382
            if ($match->getTeamA()->supportsMatchCount()) {
1383
                $match->getTeamA()->setElo($match->getTeamAEloOld());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface TeamInterface as the method setElo() does only exist in the following implementations of said interface: Team.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
1384
                $teamsReset[ $match->getTeamA()->getId() ] = true;
1385
            }
1386
            if ($match->getTeamB()->supportsMatchCount()) {
1387
                $match->getTeamB()->setElo($match->getTeamBEloOld());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface TeamInterface as the method setElo() does only exist in the following implementations of said interface: Team.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
1388
                $teamsReset[ $match->getTeamB()->getId() ] = true;
1389
            }
1390
1391
            foreach ($matches as $i => &$match) {
1392
                // Reset teams' ELOs if they haven't been reset already
1393 View Code Duplication
                if ($match->getTeamA()->supportsMatchCount() && !isset($teamsReset[ $match->getTeamA()->getId() ])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1394
                    $teamsReset[ $match->getTeamA()->getId() ] = true;
1395
                    $match->getTeamA()->setElo($match->getTeamAEloOld());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface TeamInterface as the method setElo() does only exist in the following implementations of said interface: Team.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
1396
                }
1397 View Code Duplication
                if ($match->getTeamB()->supportsMatchCount() && !isset($teamsReset[ $match->getTeamB()->getId() ])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1398
                    $teamsReset[ $match->getTeamB()->getId() ] = true;
1399
                    $match->getTeamB()->setElo($match->getTeamBEloOld());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface TeamInterface as the method setElo() does only exist in the following implementations of said interface: Team.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
1400
                }
1401
1402
                $match->recalculateElo();
1403
1404
                // Send an update to the client-side javascript, so that a
1405
                // progress bar can be updated
1406
                echo "m";
1407
            }
1408
        } catch (Exception $e) {
1409
            Database::getInstance()->rollback();
1410
            Database::getInstance()->finishTransaction();
1411
            throw $e;
1412
        }
1413
1414
        Database::getInstance()->finishTransaction();
1415
1416
        echo "\n\nCalculation successful\n";
1417
    }
1418
1419
    /**
1420
     * Get the average ELO for an array of players
1421
     *
1422
     * @param int[]|Player[] $players
1423
     *
1424
     * @return float|int
1425
     */
1426
    private static function getAveragePlayerElo($players)
1427
    {
1428
        $getElo = function ($n) {
1429
            if ($n instanceof Player) {
1430
                return $n->getElo();
1431
            }
1432
1433
            return Player::get($n)->getElo();
1434
        };
1435
1436
        return array_sum(array_map($getElo, $players)) / count($players);
1437
    }
1438
1439
    /**
1440
     * Update the match count of the teams participating in the match
1441
     *
1442
     * @param bool $decrement Whether to decrement instead of incrementing the match count
1443
     */
1444
    private function updateMatchCount($decrement = false)
1445
    {
1446
        if ($this->match_type !== self::OFFICIAL) {
1447
            return;
1448
        }
1449
1450
        $diff = ($decrement) ? -1 : 1;
1451
1452
        if ($this->isDraw()) {
1453
            $this->getTeamA()->supportsMatchCount() && $this->getTeamA()->changeMatchCount($diff, 'draw');
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface TeamInterface as the method changeMatchCount() does only exist in the following implementations of said interface: Team.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
1454
            $this->getTeamB()->supportsMatchCount() && $this->getTeamB()->changeMatchCount($diff, 'draw');
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface TeamInterface as the method changeMatchCount() does only exist in the following implementations of said interface: Team.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
1455
        } else {
1456
            $this->getWinner()->supportsMatchCount() && $this->getWinner()->changeMatchCount($diff, 'win');
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface TeamInterface as the method changeMatchCount() does only exist in the following implementations of said interface: Team.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
1457
            $this->getLoser()->supportsMatchCount()  && $this->getLoser()->changeMatchCount($diff, 'loss');
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface TeamInterface as the method changeMatchCount() does only exist in the following implementations of said interface: Team.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
1458
        }
1459
    }
1460
1461
    /**
1462
     * Update the Elos for the participating players in a match
1463
     */
1464
    private function updatePlayerElo()
1465
    {
1466
        if ($this->match_type !== self::OFFICIAL || $this->getPlayerEloDiff() === null) {
1467
            return;
1468
        }
1469
1470
        $eloDiff = $this->getPlayerEloDiff(false);
1471
1472
        foreach ($this->getTeamAPlayers() as $player) {
1473
            $player->adjustElo($eloDiff, $this);
1474
            $player->setLastMatch($this->getId());
1475
        }
1476
1477
        foreach ($this->getTeamBPlayers() as $player) {
1478
            $player->adjustElo(-$eloDiff, $this);
1479
            $player->setLastMatch($this->getId());
1480
        }
1481
    }
1482
1483
    /**
1484
     * Build an array of match participation records for a given match.
1485
     *
1486
     * @param array    $storage     The referenced array that'll be storing all of the created references.
1487
     * @param int|null $teamID      The ID of the Team this player played for, or NULL if players didn't play for a team
1488
     * @param int      $teamLoyalty Representation for team color: 0 for "Team A" or 1 for "Team B"
1489
     * @param int[]    $playerIDs   The BZiON player IDs that played for this team
1490
     * @param string[] $ipAddresses The IP addresses for the recorded players, the order must match the order of $playerIDs
1491
     * @param string[] $callsigns   The callsigns for the recorded players, the order must match the order of $playerIDs
1492
     */
1493
    private function matchParticipationEntryBuilder(array &$storage, $teamID, $teamLoyalty, array $playerIDs, array $ipAddresses = [], array $callsigns = [])
1494
    {
1495
        foreach ($playerIDs as $index => $playerID) {
1496
            if (empty($playerID)) {
1497
                continue;
1498
            }
1499
1500
            $workspace = [
1501
                'match_id' => $this->getId(),
1502
                'user_id' => $playerID,
1503
                'team_id' => $teamID,
1504
                'callsign' => __::get($callsigns, $index, null),
1505
                'ip_address' => __::get($ipAddresses, $index, null),
1506
                'team_loyalty' => $teamLoyalty,
1507
            ];
1508
1509
            $storage[] = $workspace;
1510
        }
1511
    }
1512
}
1513