Completed
Push — master ( 027456...ba1313 )
by Julien
05:54
created

SingleEliminationTreeGen::pushGroups()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 22
rs 8.9197
cc 4
eloc 11
nc 6
nop 2
1
<?php
2
3
namespace Xoco70\LaravelTournaments\TreeGen;
4
5
use Illuminate\Support\Collection;
6
use Xoco70\LaravelTournaments\Exceptions\TreeGenerationException;
7
use Xoco70\LaravelTournaments\Models\ChampionshipSettings;
8
use Xoco70\LaravelTournaments\Models\PreliminaryFight;
9
use Xoco70\LaravelTournaments\Models\SingleEliminationFight;
10
11
abstract class SingleEliminationTreeGen extends TreeGen
12
{
13
    /**
14
     * Calculate the Byes need to fill the Championship Tree.
15
     *
16
     * @param $fighters
17
     *
18
     * @return Collection
19
     */
20 View Code Duplication
    protected function getByeGroup($fighters)
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...
21
    {
22
        $fighterCount = $fighters->count();
23
        $firstRoundGroupSize = $this->firstRoundGroupSize();
24
        $treeSize = $this->getTreeSize($fighterCount, $firstRoundGroupSize);
25
        $byeCount = $treeSize - $fighterCount;
26
27
        return $this->createByeGroup($byeCount);
28
    }
29
30
    /**
31
     * Save Groups with their parent info.
32
     *
33
     * @param int $numRounds
34
     * @param int $numFighters
35
     */
36
    protected function pushGroups($numRounds, $numFighters)
37
    {
38
        // TODO Here is where you should change when enable several winners for preliminary
39
        for ($roundNumber = 2; $roundNumber <= $numRounds + 1; $roundNumber++) {
40
            // From last match to first match
41
            $maxMatches = ($numFighters / pow(2, $roundNumber));
42
43
            for ($matchNumber = 1; $matchNumber <= $maxMatches; $matchNumber++) {
44
                $fighters = $this->createByeGroup(2);
45
                $group = $this->saveGroup($matchNumber, $roundNumber, null);
46
                $this->syncGroup($group, $fighters);
47
            }
48
        }
49
        // Third place Group
50
        if ($numFighters >= $this->championship->getGroupSize() * 2) {
51
            $fighters = $this->createByeGroup(2);
52
53
            $group = $this->saveGroup($maxMatches, $numRounds, null);
0 ignored issues
show
Bug introduced by
The variable $maxMatches does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
54
55
            $this->syncGroup($group, $fighters);
56
        }
57
    }
58
59
    /**
60
     * Create empty groups after round 1.
61
     *
62
     * @param $numFighters
63
     */
64
    protected function pushEmptyGroupsToTree($numFighters)
65
    {
66
        if ($this->championship->hasPreliminary()) {
67
            /* Should add * prelimWinner but it add complexity about parent / children in tree
68
            */
69
            $numFightersElim = $numFighters / $this->settings->preliminaryGroupSize * 2;
70
            // We calculate how much rounds we will have
71
            $numRounds = intval(log($numFightersElim, 2)); // 3 rounds, but begining from round 2 ( ie => 4)
72
            return $this->pushGroups($numRounds, $numFightersElim);
73
        }
74
        // We calculate how much rounds we will have
75
        $numRounds = $this->getNumRounds($numFighters);
76
77
        return $this->pushGroups($numRounds, $numFighters);
78
    }
79
80
    /**
81
     * Chunk Fighters into groups for fighting, and optionnaly shuffle.
82
     *
83
     * @param $fightersByEntity
84
     *
85
     * @return Collection|null
86
     */
87
    protected function chunkAndShuffle(Collection $fightersByEntity)
88
    {
89
        //TODO Should Pull down to know if team or competitor
90
        if ($this->championship->hasPreliminary()) {
91
            return (new PlayOffCompetitorTreeGen($this->championship, null))->chunkAndShuffle($fightersByEntity);
0 ignored issues
show
Bug introduced by
The method chunkAndShuffle() cannot be called from this context as it is declared protected in class Xoco70\LaravelTournaments\TreeGen\PlayOffTreeGen.

This check looks for access to methods that are not accessible from the current context.

If you need to make a method accessible to another context you can raise its visibility level in the defining class.

Loading history...
92
        }
93
        $fightersGroup = null;
0 ignored issues
show
Unused Code introduced by
$fightersGroup 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...
94
95
        $fightersGroup = $fightersByEntity->chunk(2);
96
        if (!app()->runningUnitTests()) {
97
            $fightersGroup = $fightersGroup->shuffle();
98
        }
99
100
        return $fightersGroup;
101
    }
102
103
    /**
104
     * Generate First Round Fights.
105
     */
106
    protected function generateFights()
107
    {
108
        //  First Round Fights
109
        $settings = $this->settings;
110
        $initialRound = 1;
111
112
        // Very specific case to common case : Preliminary with 3 fighters
113
        if ($this->championship->hasPreliminary() && $settings->preliminaryGroupSize == 3) {
114
            // First we make all first fights of all groups
115
            // Then we make all second fights of all groups
116
            // Then we make all third fights of all groups
117
            $groups = $this->championship->groupsByRound(1)->get();
118
            for ($numFight = 1; $numFight <= $settings->preliminaryGroupSize; $numFight++) {
119
                $fight = new PreliminaryFight();
120
                $fight->saveFights($groups, $numFight);
121
            }
122
            $initialRound++;
123
        }
124
        // Save Next rounds
125
        $fight = new SingleEliminationFight();
126
        $fight->saveFights($this->championship, $initialRound);
127
    }
128
129
    /**
130
     * Return number of rounds for the tree based on fighter count.
131
     *
132
     * @param $numFighters
133
     *
134
     * @return int
135
     */
136
    protected function getNumRounds($numFighters)
137
    {
138
        return intval(log($numFighters / $this->firstRoundGroupSize() * 2, 2));
139
    }
140
141
    private function firstRoundGroupSize()
142
    {
143
        return $this->championship->hasPreliminary()
144
            ? $this->settings->preliminaryGroupSize
145
            : 2;
146
    }
147
148
    protected function generateAllTrees()
149
    {
150
        $this->minFightersCheck();
151
        $usersByArea = $this->getFightersByArea();
152
        $numFighters = count($usersByArea->collapse());
153
        $this->generateGroupsForRound($usersByArea, 1);
154
        $this->pushEmptyGroupsToTree($numFighters);
155
        $this->addParentToChildren($numFighters);
156
    }
157
158
    /**
159
     * @param Collection $usersByArea
160
     * @param $round
161
     */
162
    public function generateGroupsForRound(Collection $usersByArea, $round)
163
    {
164
        $order = 1;
165
        foreach ($usersByArea as $fightersByEntity) {
166
            // Chunking to make small round robin groups
167
            $chunkedFighters = $this->chunkAndShuffle($fightersByEntity);
168
            foreach ($chunkedFighters as $fighters) {
0 ignored issues
show
Bug introduced by
The expression $chunkedFighters of type object<Illuminate\Support\Collection>|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...
169
                $fighters = $fighters->pluck('id');
170
                if (!app()->runningUnitTests()) {
171
                    $fighters = $fighters->shuffle();
172
                }
173
                $group = $this->saveGroup($order, $round, null);
174
                $this->syncGroup($group, $fighters);
175
                $order++;
176
            }
177
        }
178
    }
179
180
    /**
181
     * Check if there is enough fighters, throw exception otherwise.
182
     *
183
     * @throws TreeGenerationException
184
     */
185
    private function minFightersCheck()
186
    {
187
        $fighters = $this->getFighters();
188
        $areas = $this->settings->fightingAreas;
189
        $fighterType = $this->settings->isTeam
190
            ? trans_choice('.team', 2)
191
            : trans_choice('laravel-tournaments::core.competitor', 2);
192
193
        $minFighterCount = $fighters->count() / $areas;
194
195
        if ($this->settings->hasPreliminary && $fighters->count() / ($this->settings->preliminaryGroupSize * $areas) < 1) {
196
            throw new TreeGenerationException(trans('laravel-tournaments::core.min_competitor_required', [
197
                'number'       => $this->settings->preliminaryGroupSize * $areas,
198
                'fighter_type' => $fighterType,
199
            ]));
200
        }
201
202
        if ($minFighterCount < ChampionshipSettings::MIN_COMPETITORS_BY_AREA) {
203
            throw new TreeGenerationException(trans('laravel-tournaments::core.min_competitor_required', [
204
                'number'       => ChampionshipSettings::MIN_COMPETITORS_BY_AREA,
205
                'fighter_type' => $fighterType,
206
            ]));
207
        }
208
    }
209
}
210