Completed
Push — master ( 26d986...9b7bb9 )
by Julien
09:29
created

SingleEliminationTreeGen::minFightersCheck()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 8.439
c 0
b 0
f 0
cc 5
eloc 15
nc 6
nop 0
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\SingleEliminationFight;
9
use Xoco70\LaravelTournaments\Models\PreliminaryFight;
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
        return $this->createByeGroup($byeCount);
27
    }
28
29
    /**
30
     * Save Groups with their parent info.
31
     *
32
     * @param int $numRounds
33
     * @param int $numFighters
34
     */
35 View Code Duplication
    protected function pushGroups($numRounds, $numFighters)
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...
36
    {
37
        // TODO Here is where you should change when enable several winners for preliminary
38
        for ($roundNumber = 2; $roundNumber <= $numRounds + 1; $roundNumber++) {
39
            // From last match to first match
40
            $maxMatches = ($numFighters / pow(2, $roundNumber));
41
42
            for ($matchNumber = 1; $matchNumber <= $maxMatches; $matchNumber++) {
43
                $fighters = $this->createByeGroup(2);
44
                $group = $this->saveGroup($matchNumber, $roundNumber, null);
45
                $this->syncGroup($group, $fighters);
46
            }
47
        }
48
    }
49
50
    /**
51
     * Create empty groups for direct Elimination Tree.
52
     *
53
     * @param $numFighters
54
     */
55
    protected function pushEmptyGroupsToTree($numFighters)
56
    {
57
        if ($this->championship->hasPreliminary()) {
58
            $numFightersElim = $numFighters / $this->championship->getSettings()->preliminaryGroupSize * 2;
59
            // We calculate how much rounds we will have
60
            $numRounds = intval(log($numFightersElim, 2)); // 3 rounds, but begining from round 2 ( ie => 4)
61
            return $this->pushGroups($numRounds, $numFightersElim);
62
        }
63
        // We calculate how much rounds we will have
64
        $numRounds = $this->getNumRounds($numFighters);
65
66
        return $this->pushGroups($numRounds, $numFighters);
67
    }
68
69
    /**
70
     * Chunk Fighters into groups for fighting, and optionnaly shuffle.
71
     *
72
     * @param $fightersByEntity
73
     *
74
     * @return Collection|null
75
     */
76
    protected function chunkAndShuffle(Collection $fightersByEntity)
77
    {
78
        //TODO Should Pull down to know if team or competitor
79
        if ($this->championship->hasPreliminary()) {
80
            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...
81
        }
82
        $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...
83
84
        $fightersGroup = $fightersByEntity->chunk(2);
85
        if (!app()->runningUnitTests()) {
86
            $fightersGroup = $fightersGroup->shuffle();
87
        }
88
89
        return $fightersGroup;
90
    }
91
92
    /**
93
     * Generate First Round Fights.
94
     */
95
    protected function generateFights()
96
    {
97
        //  First Round Fights
98
        $settings = $this->championship->getSettings();
99
        $initialRound = 1;
100
101
        // Very specific case to common case : Preliminary with 3 fighters
102
        if ($this->championship->hasPreliminary() && $settings->preliminaryGroupSize == 3) {
103
            // First we make all first fights of all groups
104
            // Then we make all second fights of all groups
105
            // Then we make all third fights of all groups
106
            $groups = $this->championship->groupsByRound(1)->get();
107
            for ($numFight = 1; $numFight <= $settings->preliminaryGroupSize; $numFight++) {
108
                $fight = new PreliminaryFight();
109
                $fight->saveFights($groups, $numFight);
110
            }
111
            $initialRound++;
112
        }
113
        // Save Next rounds
114
        $fight = new SingleEliminationFight();
115
        $fight->saveFights($this->championship, $initialRound);
116
    }
117
118
    /**
119
     * Return number of rounds for the tree based on fighter count.
120
     *
121
     * @param $numFighters
122
     *
123
     * @return int
124
     */
125
    protected function getNumRounds($numFighters)
126
    {
127
        return intval(log($numFighters / $this->firstRoundGroupSize() * 2, 2));
128
    }
129
130
    private function firstRoundGroupSize()
131
    {
132
        return $this->championship->hasPreliminary()
133
            ? $this->championship->getSettings()->preliminaryGroupSize
134
            : 2;
135
    }
136
137
    protected function generateAllTrees()
138
    {
139
        $this->minFightersCheck();
140
        $usersByArea = $this->getFightersByArea();
141
        $numFighters = count($usersByArea->collapse());
142
        $this->generateGroupsForRound($usersByArea, 1);
143
        $this->pushEmptyGroupsToTree($numFighters); // Abstract
144
        $this->addParentToChildren($numFighters);
145
146
    }
147
148
    /**
149
     * @param Collection $usersByArea
150
     * @param $round
151
     */
152
    public function generateGroupsForRound(Collection $usersByArea, $round)
153
    {
154
        $order = 1;
155
        foreach ($usersByArea as $fightersByEntity) {
156
            // Chunking to make small round robin groups
157
            $chunkedFighters = $this->chunkAndShuffle($fightersByEntity);
158
            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...
159
                $fighters = $fighters->pluck('id');
160
                if (!app()->runningUnitTests()) {
161
                    $fighters = $fighters->shuffle();
162
                }
163
                $group = $this->saveGroup($order, $round, null);
164
                $this->syncGroup($group, $fighters);
165
                $order++;
166
            }
167
        }
168
    }
169
170
    /**
171
     * Check if there is enough fighters, throw exception otherwise
172
     * @throws TreeGenerationException
173
     */
174
    private function minFightersCheck()
175
    {
176
        $fighters = $this->getFighters();
177
        $areas = $this->settings->fightingAreas;
178
        $fighterType = $this->settings->isTeam
179
            ? trans_choice('.team', 2)
180
            : trans_choice('laravel-tournaments::core.competitor', 2);
181
182
        $minFighterCount = $fighters->count() / $areas;
183
184
185
        if ($this->settings->hasPreliminary && $fighters->count() / ($this->settings->preliminaryGroupSize * $areas) < 1) {
186
            throw new TreeGenerationException(trans('laravel-tournaments::core.min_competitor_required', [
187
                'number' => $this->settings->preliminaryGroupSize * $areas,
188
                'fighter_type' => $fighterType
189
            ]));
190
        }
191
192
        if ($minFighterCount < ChampionshipSettings::MIN_COMPETITORS_BY_AREA) {
193
            throw new TreeGenerationException(trans('laravel-tournaments::core.min_competitor_required', [
194
                'number' => ChampionshipSettings::MIN_COMPETITORS_BY_AREA,
195
                'fighter_type' => $fighterType
196
            ]));
197
        }
198
    }
199
}
200