Completed
Push — feature/team-activity ( 2f8466 )
by Vladimir
02:53
created

Team::getActivity()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
/**
3
 * This file contains functionality relating to the teams belonging to the current 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
9
/**
10
 * A league team
11
 * @package    BZiON\Models
12
 */
13
class Team extends AvatarModel implements TeamInterface, DuplexUrlInterface, EloInterface
14
{
15
    /**
16
     * The description of the team written in markdown
17
     *
18
     * @var string
19
     */
20
    protected $description;
21
22
    /**
23
     * The creation date of the team
24
     *
25
     * @var TimeDate
26
     */
27
    protected $created;
28
29
    /**
30
     * The team's current elo
31
     *
32
     * @var int
33
     */
34
    protected $elo;
35
36
    /**
37
     * The team's activity
38
     *
39
     * null if we haven't calculated it yet
40
     *
41
     * @var float|null
42
     */
43
    protected $activity = null;
44
45
    /**
46
     * The id of the team leader
47
     *
48
     * @var int
49
     */
50
    protected $leader;
51
52
    /**
53
     * The number of matches won
54
     *
55
     * @var int
56
     */
57
    protected $matches_won;
58
59
    /**
60
     * The number of matches lost
61
     *
62
     * @var int
63
     */
64
    protected $matches_lost;
65
66
    /**
67
     * The number of matches tied
68
     *
69
     * @var int
70
     */
71
    protected $matches_draw;
72
73
    /**
74
     * The total number of matches
75
     *
76
     * @var int
77
     */
78
    protected $matches_total;
79
80
    /**
81
     * The number of members
82
     *
83
     * @var int
84
     */
85
    protected $members;
86
87
    /**
88
     * The team's status
89
     *
90
     * @var string
91
     */
92
    protected $status;
93
94
    /**
95
     * The name of the database table used for queries
96
     */
97
    const TABLE = "teams";
98
99
    /**
100
     * The location where avatars will be stored
101
     */
102
    const AVATAR_LOCATION = "/web/assets/imgs/avatars/teams/";
103
104
    const CREATE_PERMISSION = Permission::CREATE_TEAM;
105
    const EDIT_PERMISSION = Permission::EDIT_TEAM;
106
    const SOFT_DELETE_PERMISSION = Permission::SOFT_DELETE_TEAM;
107
    const HARD_DELETE_PERMISSION = Permission::HARD_DELETE_TEAM;
108
109
    /**
110
     * {@inheritdoc}
111
     */
112
    protected function assignResult($team)
113
    {
114
        $this->name = $team['name'];
115
        $this->alias = $team['alias'];
116
        $this->description = $team['description'];
117
        $this->avatar = $team['avatar'];
118
        $this->created = TimeDate::fromMysql($team['created']);
119
        $this->elo = $team['elo'];
120
        $this->leader = $team['leader'];
121
        $this->matches_won = $team['matches_won'];
122
        $this->matches_lost = $team['matches_lost'];
123
        $this->matches_draw = $team['matches_draw'];
124
        $this->members = $team['members'];
125
        $this->status = $team['status'];
126
127
        $this->matches_total = $this->matches_won + $this->matches_lost + $this->matches_draw;
128
129
        $this->activity = isset($team['activity']) ? $team['activity'] : 0;
130
    }
131
132
    /**
133
     * Adds a new member to the team
134
     *
135
     * @param int $id The id of the player to add to the team
136
     *
137
     * @return bool|null True if both the player was added to the team AND the team member count was incremented
138
     */
139 View Code Duplication
    public function addMember($id)
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...
140
    {
141
        $player = Player::get($id);
142
143
        if (!$player->isTeamless()) {
144
            throw new Exception("The player already belongs in a team");
145
        }
146
147
        $player->setTeam($this->getId());
148
        $this->update('members', ++$this->members);
149
    }
150
151
    /**
152
     * Increase or decrease the ELO of the team
153
     *
154
     * @param int   $adjust The value to be added to the current ELO (negative to subtract)
155
     * @param Match $match  The match where this Elo change took place
156
     */
157
    public function adjustElo($adjust, Match $match = null)
158
    {
159
        $this->elo += $adjust;
160
        $this->update("elo", $this->elo);
161
    }
162
163
    /**
164
     * Change the ELO of the team
165
     *
166
     * @param int $elo The new team ELO
167
     */
168
    public function setElo($elo)
169
    {
170
        $this->updateProperty($this->elo, "elo", $elo);
171
    }
172
173
    /**
174
     * Increment the team's match count
175
     *
176
     * @param int    $adjust The number to add to the current matches number (negative to substract)
177
     * @param string $type   The match count that should be changed. Can be 'win', 'draw' or 'loss'
178
     */
179
    public function changeMatchCount($adjust, $type)
180
    {
181
        $this->matches_total += $adjust;
182
183
        switch ($type) {
184
            case "win":
185
            case "won":
186
                $this->update("matches_won", $this->matches_won += $adjust);
187
188
                return;
189
            case "loss":
190
            case "lost":
191
                $this->update("matches_lost", $this->matches_lost += $adjust);
192
193
                return;
194
            default:
195
                $this->update("matches_draw", $this->matches_draw += $adjust);
196
197
                return;
198
        }
199
    }
200
201
    /**
202
     * Decrement the team's match count by one
203
     *
204
     * @param string $type The type of the match. Can be 'win', 'draw' or 'loss'
205
     */
206
    public function decrementMatchCount($type)
207
    {
208
        $this->changeMatchCount(-1, $type);
209
    }
210
211
    /**
212
     * Get the activity of the team
213
     *
214
     * @return float The team's activity
215
     */
216
    public function getActivity()
217
    {
218
        return $this->activity;
219
    }
220
221
    /**
222
     * Get the creation date of the team
223
     *
224
     * @return TimeDate The creation date of the team
225
     */
226
    public function getCreationDate()
227
    {
228
        return $this->created->copy();
229
    }
230
231
    /**
232
     * Get the description of the team
233
     *
234
     * @return string  The description of the team
235
     */
236
    public function getDescription()
237
    {
238
        return $this->description;
239
    }
240
241
    /**
242
     * Get the current elo of the team
243
     *
244
     * @return int The elo of the team
245
     */
246
    public function getElo()
247
    {
248
        return $this->elo;
249
    }
250
251
    /**
252
     * Get the leader of the team
253
     *
254
     * @return Player The object representing the team leader
255
     */
256
    public function getLeader()
257
    {
258
        return Player::get($this->leader);
259
    }
260
261
    /**
262
     * Get the matches this team has participated in
263
     *
264
     * @param string $matchType The filter for match types: "all", "wins", "losses", or "draws"
265
     * @param int    $count     The amount of matches to be retrieved
266
     * @param int    $page      The number of the page to return
267
     *
268
     * @return Match[] The array of match IDs this team has participated in
269
     */
270
    public function getMatches($matchType = "all", $count = 5, $page = 1)
271
    {
272
        return Match::getQueryBuilder()
273
             ->active()
274
             ->with($this, $matchType)
275
             ->sortBy('time')->reverse()
276
             ->limit($count)->fromPage($page)
277
             ->getModels($fast = true);
278
    }
279
280
    /**
281
     * Get the number of matches that resulted as a draw
282
     *
283
     * @return int The number of matches, respectively
284
     */
285
    public function getMatchesDraw()
286
    {
287
        return $this->matches_draw;
288
    }
289
290
    /**
291
     * Get the number of matches that the team has lost
292
     *
293
     * @return int The number of matches, respectively
294
     */
295
    public function getMatchesLost()
296
    {
297
        return $this->matches_lost;
298
    }
299
300
    /**
301
     * Get the URL that points to the team's list of matches
302
     *
303
     * @return string The team's list of matches
304
     */
305
    public function getMatchesURL()
306
    {
307
        return Service::getGenerator()->generate("match_by_team_list", array("team" => $this->getAlias()));
308
    }
309
310
    /**
311
     * Get the number of matches that the team has won
312
     *
313
     * @return int The number of matches, respectively
314
     */
315
    public function getMatchesWon()
316
    {
317
        return $this->matches_won;
318
    }
319
320
    /**
321
     * Get the members on the team
322
     *
323
     * @return Player[] The members on the team
324
     */
325
    public function getMembers()
326
    {
327
        $leader = $this->leader;
328
        $members = Player::getTeamMembers($this->id);
329
330
        usort($members, function ($a, $b) use ($leader) {
331
            // Leader always goes first
332
            if ($a->getId() == $leader) {
333
                return -1;
334
            }
335
            if ($b->getId() == $leader) {
336
                return 1;
337
            }
338
339
            // Sort the rest of the players alphabetically
340
            $sort = Player::getAlphabeticalSort();
341
342
            return $sort($a, $b);
343
        });
344
345
        return $members;
346
    }
347
348
    /**
349
     * Get the name of the team
350
     *
351
     * @return string The name of the team
352
     */
353
    public function getName()
354
    {
355
        if ($this->name === null) {
356
            return "None";
357
        }
358
        return $this->name;
359
    }
360
361
    /**
362
     * Get the name of the team, safe for use in your HTML
363
     *
364
     * @return string The name of the team
365
     */
366
    public function getEscapedName()
367
    {
368
        if (!$this->valid) {
369
            return "<em>None</em>";
370
        }
371
        return $this->escape($this->name);
372
    }
373
374
    /**
375
     * Get the number of members on the team
376
     *
377
     * @return int The number of members on the team
378
     */
379
    public function getNumMembers()
380
    {
381
        return $this->members;
382
    }
383
384
    /**
385
     * Get the total number of matches this team has played
386
     *
387
     * @return int The total number of matches this team has played
388
     */
389
    public function getNumTotalMatches()
390
    {
391
        return $this->matches_total;
392
    }
393
394
    /**
395
     * Get the rank category a team belongs too based on their ELO
396
     *
397
     * This value is always a multiple of 100 and less than or equal to 2000
398
     *
399
     * @return int The rank category a team belongs to
400
     */
401
    public function getRankValue()
402
    {
403
        return min(2000, floor($this->getElo() / 100) * 100);
404
    }
405
406
    /**
407
     * Get the HTML for an image with the rank symbol
408
     *
409
     * @return string The HTML for a rank image
410
     */
411
    public function getRankImageLiteral()
412
    {
413
        return '<div class="c-rank c-rank--' . $this->getRankValue() . '" aria-hidden="true"></div>';
414
    }
415
416
    /**
417
     * Increment the team's match count by one
418
     *
419
     * @param string $type The type of the match. Can be 'win', 'draw' or 'loss'
420
     */
421
    public function incrementMatchCount($type)
422
    {
423
        $this->changeMatchCount(1, $type);
424
    }
425
426
    /**
427
     * Check if a player is part of this team
428
     *
429
     * @param int $playerID The player to check
430
     *
431
     * @return bool True if the player belongs to this team
432
     */
433
    public function isMember($playerID)
434
    {
435
        $player = Player::get($playerID);
436
437
        return $player->getTeam()->isSameAs($this);
438
    }
439
440
    /**
441
     * Removes a member from the team
442
     *
443
     * @param  int  $id The id of the player to remove
444
     * @return void
445
     */
446 View Code Duplication
    public function removeMember($id)
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...
447
    {
448
        if (!$this->isMember($id)) {
449
            throw new Exception("The player is not a member of that team");
450
        }
451
452
        $player = Player::get($id);
453
454
        $player->update("team", null);
455
        $this->update('members', --$this->members);
456
    }
457
458
    /**
459
     * Update the description of the team
460
     *
461
     * @param  string $description The description of the team written as markdown
462
     * @return void
463
     */
464
    public function setDescription($description)
465
    {
466
        $this->update("description", $description);
467
    }
468
469
    /**
470
     * Change the status of the team
471
     *
472
     * @param  string $newStatus The new status of the team (open, closed, disabled or deleted)
473
     * @return self
474
     */
475
    public function setStatus($newStatus)
476
    {
477
        return $this->updateProperty($this->status, 'status', $newStatus);
478
    }
479
480
    /**
481
     * Change the leader of the team
482
     *
483
     * @param  int  $leader The ID of the new leader of the team
484
     * @return self
485
     */
486
    public function setLeader($leader)
487
    {
488
        return $this->updateProperty($this->leader, 'leader', $leader);
489
    }
490
491
    /**
492
     * Find if a specific match is the team's last one
493
     *
494
     * @param  int|Match $match The match
495
     * @return bool
496
     */
497
    public function isLastMatch($match)
498
    {
499
        // Find if this team participated in any matches after the current match
500
        return !Match::getQueryBuilder()
501
            ->with($this)
502
            ->where('status')->notEquals('deleted')
503
            ->where('time')->isAfter(Match::get($match)->getTimestamp())
504
            ->any();
505
    }
506
507
    /**
508
     * {@inheritdoc}
509
     */
510
    public function delete()
511
    {
512
        parent::delete();
513
514
        // Remove all the members of a deleted team
515
        $this->updateProperty($this->members, 'members', 0);
516
        $this->db->execute('UPDATE players SET team = NULL WHERE team = ?', $this->id);
517
    }
518
519
    /**
520
     * {@inheritdoc}
521
     */
522
    public function supportsMatchCount()
523
    {
524
        return $this->isValid();
525
    }
526
527
    /**
528
     * Create a new team
529
     *
530
     * @param  string           $name        The name of the team
531
     * @param  int              $leader      The ID of the person creating the team, also the leader
532
     * @param  string           $avatar      The URL to the team's avatar
533
     * @param  string           $description The team's description
534
     * @param  string           $status      The team's status (open, closed, disabled or deleted)
535
     * @param  string|\TimeDate $created     The date the team was created
536
     *
537
     * @return Team   An object that represents the newly created team
538
     */
539
    public static function createTeam($name, $leader, $avatar, $description, $status = 'closed', $created = "now")
540
    {
541
        $created = TimeDate::from($created);
542
543
        $team = self::create(array(
544
            'name'         => $name,
545
            'alias'        => self::generateAlias($name),
546
            'description'  => $description,
547
            'elo'          => 1200,
548
            'activity'     => 0.00,
549
            'matches_won'  => 0,
550
            'matches_draw' => 0,
551
            'matches_lost' => 0,
552
            'members'      => 0,
553
            'avatar'       => $avatar,
554
            'leader'       => $leader,
555
            'status'       => $status,
556
            'created'      => $created->toMysql(),
557
        ));
558
559
        $team->addMember($leader);
560
        $team->getIdenticon($team->getId());
561
562
        return $team;
563
    }
564
565
    /**
566
     * Get all the teams in the database that are not disabled or deleted
567
     *
568
     * @return Team[] An array of Team IDs
569
     */
570
    public static function getTeams()
571
    {
572
        return self::arrayIdToModel(
573
            self::fetchIdsFrom(
574
                "status", array("disabled", "deleted"),
575
                true, "ORDER BY elo DESC"
576
            )
577
        );
578
    }
579
580
    /**
581
     * Get a single team by its name
582
     *
583
     * @param  string $name The team name to look for
584
     * @return Team
585
     */
586
    public static function getFromName($name)
587
    {
588
        $team = static::get(self::fetchIdFrom($name, 'name'));
589
590
        return $team->inject('name', $name);
591
    }
592
593
    /**
594
     * Alphabetical order function for use in usort (case-insensitive)
595
     * @return Closure The sort function
596
     */
597
    public static function getAlphabeticalSort()
598
    {
599
        return function (Team $a, Team $b) {
600
            return strcasecmp($a->getName(), $b->getName());
601
        };
602
    }
603
604
    /**
605
     * {@inheritdoc}
606
     */
607
    public static function getActiveStatuses()
608
    {
609
        return array('open', 'closed');
610
    }
611
612
    /**
613
     * {@inheritdoc}
614
     */
615
    public static function getEagerColumns($prefix = null)
616
    {
617
        $columns = [
618
            'id',
619
            'name',
620
            'alias',
621
            'description',
622
            'avatar',
623
            'created',
624
            'elo',
625
            'leader',
626
            'matches_won',
627
            'matches_lost',
628
            'matches_draw',
629
            'members',
630
            'status',
631
        ];
632
633
        return self::formatColumns($prefix, $columns);
634
    }
635
636
    /**
637
     * Get a query builder for teams
638
     * @return TeamQueryBuilder
639
     */
640
    public static function getQueryBuilder()
641
    {
642
        return new TeamQueryBuilder('Team', array(
643
            'columns' => array(
644
                'name'    => 'name',
645
                'elo'     => 'elo',
646
                'leader'  => 'leader',
647
                'members' => 'members',
648
                'status'  => 'status'
649
            ),
650
            'name' => 'name',
651
        ));
652
    }
653
654
    /**
655
     * {@inheritdoc}
656
     */
657
    protected function isEditor($player)
658
    {
659
        return $player->isSameAs($this->getLeader());
660
    }
661
}
662