Completed
Push — master ( 17e0da...c0bdc3 )
by Julien
07:40
created

DirectEliminationTreeGen::generateGroupsForRound()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 17
rs 9.2
cc 4
eloc 11
nc 4
nop 2
1
<?php
2
3
namespace Xoco70\LaravelTournaments\TreeGen;
4
5
use Illuminate\Support\Collection;
6
use Xoco70\LaravelTournaments\Models\DirectEliminationFight;
7
use Xoco70\LaravelTournaments\Models\PreliminaryFight;
8
9
abstract class DirectEliminationTreeGen extends TreeGen
10
{
11
    /**
12
     * Calculate the Byes need to fill the Championship Tree.
13
     *
14
     * @param $fighters
15
     *
16
     * @return Collection
17
     */
18 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...
19
    {
20
        $fighterCount = $fighters->count();
21
        $firstRoundGroupSize = $this->firstRoundGroupSize();
22
        $treeSize = $this->getTreeSize($fighterCount, $firstRoundGroupSize);
23
        $byeCount = $treeSize - $fighterCount;
24
        return $this->createByeGroup($byeCount);
25
    }
26
27
    /**
28
     * Save Groups with their parent info.
29
     *
30
     * @param int $numRounds
31
     * @param int $numFighters
32
     */
33 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...
34
    {
35
        // TODO Here is where you should change when enable several winners for preliminary
36
        for ($roundNumber = 2; $roundNumber <= $numRounds + 1; $roundNumber++) {
37
            // From last match to first match
38
            $maxMatches = ($numFighters / pow(2, $roundNumber));
39
40
            for ($matchNumber = 1; $matchNumber <= $maxMatches; $matchNumber++) {
41
                $fighters = $this->createByeGroup(2);
42
                $group = $this->saveGroup($matchNumber, $roundNumber, null);
43
                $this->syncGroup($group, $fighters);
44
            }
45
        }
46
    }
47
48
    /**
49
     * Create empty groups for direct Elimination Tree.
50
     *
51
     * @param $numFighters
52
     */
53
    protected function pushEmptyGroupsToTree($numFighters)
54
    {
55
        if ($this->championship->hasPreliminary()) {
56
            $numFightersElim = $numFighters / $this->championship->getSettings()->preliminaryGroupSize * 2;
57
            // We calculate how much rounds we will have
58
            $numRounds = intval(log($numFightersElim, 2)); // 3 rounds, but begining from round 2 ( ie => 4)
59
            return $this->pushGroups($numRounds, $numFightersElim);
60
        }
61
        // We calculate how much rounds we will have
62
        $numRounds = $this->getNumRounds($numFighters);
63
64
        return $this->pushGroups($numRounds, $numFighters);
65
    }
66
67
    /**
68
     * Chunk Fighters into groups for fighting, and optionnaly shuffle.
69
     *
70
     * @param $fightersByEntity
71
     *
72
     * @return Collection|null
73
     */
74
    protected function chunkAndShuffle(Collection $fightersByEntity)
75
    {
76
        //TODO Should Pull down to know if team or competitor
77
        if ($this->championship->hasPreliminary()) {
78
            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...
79
        }
80
        $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...
81
82
        $fightersGroup = $fightersByEntity->chunk(2);
83
        if (!app()->runningUnitTests()) {
84
            $fightersGroup = $fightersGroup->shuffle();
85
        }
86
87
        return $fightersGroup;
88
    }
89
90
    /**
91
     * Generate First Round Fights.
92
     */
93
    protected function generateFights()
94
    {
95
        //  First Round Fights
96
        $settings = $this->championship->getSettings();
97
        $initialRound = 1;
98
99
        // Very specific case to common case : Preliminary with 3 fighters
100
        if ($this->championship->hasPreliminary() && $settings->preliminaryGroupSize == 3) {
101
            // First we make all first fights of all groups
102
            // Then we make all second fights of all groups
103
            // Then we make all third fights of all groups
104
            $groups = $this->championship->groupsByRound(1)->get();
105
            for ($numFight = 1; $numFight <= $settings->preliminaryGroupSize; $numFight++) {
106
                $fight = new PreliminaryFight();
107
                $fight->saveFights($groups, $numFight);
108
            }
109
            $initialRound++;
110
        }
111
        // Save Next rounds
112
        $fight = new DirectEliminationFight();
113
        $fight->saveFights($this->championship, $initialRound);
114
    }
115
116
    /**
117
     * Return number of rounds for the tree based on fighter count.
118
     *
119
     * @param $numFighters
120
     *
121
     * @return int
122
     */
123
    protected function getNumRounds($numFighters)
124
    {
125
        return intval(log($numFighters / $this->firstRoundGroupSize() * 2, 2));
126
    }
127
128
    private function firstRoundGroupSize()
129
    {
130
        return $this->championship->hasPreliminary()
131
            ? $this->championship->getSettings()->preliminaryGroupSize
132
            : 2;
133
    }
134
135
    protected function generateAllTrees()
136
    {
137
        $usersByArea = $this->getFightersByArea();
138
        $numFighters = count($usersByArea->collapse());
139
        $this->generateGroupsForRound($usersByArea, 1);
140
        $this->pushEmptyGroupsToTree($numFighters); // Abstract
141
        $this->addParentToChildren($numFighters);
142
143
    }
144
    /**
145
     * @param Collection $usersByArea
146
     * @param $round
147
     */
148
    public function generateGroupsForRound(Collection $usersByArea, $round)
149
    {
150
        $order = 1;
151
        foreach ($usersByArea as $fightersByEntity) {
152
            // Chunking to make small round robin groups
153
            $chunkedFighters = $this->chunkAndShuffle($fightersByEntity);
154
            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...
155
                $fighters = $fighters->pluck('id');
156
                if (!app()->runningUnitTests()) {
157
                    $fighters = $fighters->shuffle();
158
                }
159
                $group = $this->saveGroup($order, $round, null);
160
                $this->syncGroup($group, $fighters);
161
                $order++;
162
            }
163
        }
164
    }
165
}
166