DrawKnockOut   A
last analyzed

Complexity

Total Complexity 19

Size/Duplication

Total Lines 158
Duplicated Lines 10.13 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 19
c 1
b 0
f 0
lcom 1
cbo 4
dl 16
loc 158
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A listOfAvailableTeamsAmount() 0 4 1
A setTournament() 0 14 2
A determineRound() 0 8 2
A handle() 0 12 3
B draw() 0 15 5
B getPairs() 0 26 2
B savePairs() 16 34 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace App\Jobs\Tournament;
4
5
use App\Match;
6
use App\Tournament;
7
use Illuminate\Support\Collection;
8
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
9
10
/**
11
 * Class DrawKnockOut
12
 * @package App\Jobs\Tournament
13
 */
14
class DrawKnockOut extends Job
15
{
16
    /**
17
     * @var Collection
18
     */
19
    protected $teams;
20
21
    /**
22
     * @var EloquentCollection
23
     */
24
    protected $matches;
25
26
    /**
27
     * @var int
28
     */
29
    protected $round;
30
31
    /**
32
     * @return array
33
     */
34
    private static function listOfAvailableTeamsAmount()
35
    {
36
        return [2, 4, 8, 16, 32, 64];
37
    }
38
39
    /**
40
     * @name setTournament
41
     * @param Tournament $tournament
42
     */
43
    protected function setTournament(Tournament $tournament)
44
    {
45
        $this->teams = new Collection();
46
        $this->tournament = $tournament;
47
48
        foreach ($this->tournament->tournamentTeams()->getResults() as $team) {
49
            $this->teams->push([
50
                'id' => $team->id,
51
                'name' => $team->team->name
52
            ]);
53
        }
54
55
        $this->round = $tournament->getCurrentRound() + 1;
56
    }
57
58
    protected function determineRound()
59
    {
60
        if ($this->tournament->matches()->get()->count() === 0) {
61
            $this->round = 1;
62
        } else {
63
            $this->round = $this->tournament->currentRound() + 1;
0 ignored issues
show
Bug introduced by
The method currentRound() does not exist on App\Tournament. Did you maybe mean getCurrentRound()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
64
        }
65
    }
66
67
    /**
68
     * Execute the job.
69
     *
70
     * @return void
71
     * @throws \UnexpectedValueException
72
     */
73
    public function handle()
74
    {
75
        if (Tournament::MIN_TEAMS_AMOUNT > count($this->teams)) {
76
            throw new \UnexpectedValueException('Tournament should have at least 2 teams.');
77
        }
78
79
        if (!in_array(count($this->teams), self::listOfAvailableTeamsAmount())) {
80
            throw new \UnexpectedValueException('Amount of teams should be a 2, 4, 8, 16, 32 or 64.');
81
        }
82
83
        $this->draw();
84
    }
85
86
    public function draw()
87
    {
88
        $pairs = $this->getPairs();
89
90
        if ($pairs->count() > 0 && $pairs->get(0)->count() > 1) {
91
            $gameType = Match::GAME_TYPE_QUALIFY;
92
93
            // set game type to `final` when there is only 1 pair left in the tournament
94
            if ($this->round !== 1 && 1 === $pairs->count()) {
95
                $gameType = Match::GAME_TYPE_FINAL;
96
            }
97
98
            $this->savePairs($pairs, $gameType);
99
        }
100
    }
101
102
    /**
103
     * @return Collection
104
     */
105
    protected function getPairs()
106
    {
107
        $round = $this->round;
108
        $tournament = $this->tournament;
109
110
        if (1 === $round) {
111
            $this->teams = $this->teams->shuffle();
112
113
            return $this->teams->chunk(2);
114
        } else {
115
            $currentPairs = $tournament->getPairs()->filter(function ($pair) use ($round) {
116
                return $pair->get('round') === $round - 1;
117
            });
118
119
            $roundWinners = new Collection();
120
121
            $currentPairs->each(function ($pair) use ($tournament, $roundWinners) {
122
                // detect pair winner
123
                $roundWinners->push($tournament->getScore($pair->get('matches'))->first());
0 ignored issues
show
Bug introduced by
The method first does only exist in Illuminate\Support\Collection, but not in App\Tournament.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
124
            });
125
126
            return $this->teams->filter(function ($team) use ($roundWinners) {
127
                return $roundWinners->pluck('teamId')->contains($team['id']);
128
            })->chunk(2);
129
        }
130
    }
131
132
    /**
133
     * @name savePairs
134
     * @param $pairs
135
     * @param string $gameType
136
     */
137
    protected function savePairs($pairs, $gameType = Match::GAME_TYPE_QUALIFY)
138
    {
139
        $defaults = [
140
            'homeScore' => 0,
141
            'awayScore' => 0,
142
            'homePenaltyScore' => 0,
143
            'awayPenaltyScore' => 0,
144
            'round' => $this->round,
145
            'gameType' => $gameType,
146
            'resultType' => Match::RESULT_TYPE_UNKNOWN,
147
            'status' => Match::STATUS_NOT_STARTED
148
        ];
149
150 View Code Duplication
        foreach ($pairs as $pair) {
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...
151
            $this->tournament->matches()->create(
152
                array_merge($defaults, [
153
                    'homeTournamentTeamId' => array_get($pair->first(), 'id'),
154
                    'awayTournamentTeamId' => array_get($pair->last(), 'id'),
155
                ])
156
            );
157
        }
158
159
        // generate reverse matches only for match with `qualify` type
160
        if (Match::GAME_TYPE_QUALIFY === $gameType) {
161 View Code Duplication
            foreach ($pairs as $pair) {
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...
162
                $this->tournament->matches()->create(
163
                    array_merge($defaults, [
164
                        'awayTournamentTeamId' => array_get($pair->first(), 'id'),
165
                        'homeTournamentTeamId' => array_get($pair->last(), 'id'),
166
                    ])
167
                );
168
            }
169
        }
170
    }
171
}
172