Completed
Push — master ( b13aa8...0a3a64 )
by Julien
11:57
created

DirectEliminationTreeGen::pushGroups()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 13
Ratio 100 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 13
loc 13
rs 9.4285
cc 3
eloc 7
nc 3
nop 2
1
<?php
2
3
namespace Xoco70\KendoTournaments\TreeGen;
4
5
use Illuminate\Support\Collection;
6
use Illuminate\Support\Facades\App;
7
use Xoco70\KendoTournaments\Models\Championship;
8
use Xoco70\KendoTournaments\Models\DirectEliminationFight;
9
use Xoco70\KendoTournaments\Models\Fight;
10
11
class DirectEliminationTreeGen extends TreeGen
12
{
13
14
    /**
15
     * Calculate the Byes need to fill the Championship Tree.
16
     * @param $fighters
17
     * @return Collection
18
     */
19
    protected function getByeGroup($fighters)
20
    {
21
        $fighterCount = $fighters->count();
22
        $treeSize = $this->getTreeSize($fighterCount, 2);
23
        $byeCount = $treeSize - $fighterCount;
24
25
        return $this->createNullsGroup($byeCount);
26
    }
27
28
29
    /**
30
     * Create empty groups for direct Elimination Tree
31
     * @param $numFightersElim
32
     */
33
    public function pushEmptyGroupsToTree($numFightersElim)
34
    {
35
        // We calculate how much rounds we will have
36
        $numRounds = intval(log($numFightersElim, 2));
37
        $this->pushGroups($numRounds, $numFightersElim);
38
    }
39
40
    /**
41
     * Chunk Fighters into groups for fighting, and optionnaly shuffle
42
     * @param $fightersByEntity
43
     * @return Collection|null
44
     */
45
    protected function chunkAndShuffle($round = null, $fightersByEntity)
0 ignored issues
show
Unused Code introduced by
The parameter $round is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
46
    {
47
        $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...
48
49
        $fightersGroup = $fightersByEntity->chunk(2);
50
        if (!App::runningUnitTests()) {
51
            $fightersGroup = $fightersGroup->shuffle();
52
        }
53
        return $fightersGroup;
54
    }
55
56
57
    /**
58
     * Generate First Round Fights
59
     */
60
    public function generateFights()
61
    {
62
        parent::destroyPreviousFights($this->championship);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (destroyPreviousFights() instead of generateFights()). Are you sure this is correct? If so, you might want to change this to $this->destroyPreviousFights().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
Unused Code introduced by
The call to TreeGen::destroyPreviousFights() has too many arguments starting with $this->championship.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
63
        DirectEliminationFight::saveFights($this->championship);
64
    }
65
    /**
66
     *
67
     */
68
    public function generateNextRoundsFights()
69
    {
70
        $fightersCount = $this->championship->competitors->count() + $this->championship->teams->count();
71
        $maxRounds = intval(ceil(log($fightersCount, 2)));
72
        for ($numRound = 1; $numRound < $maxRounds; $numRound++) {
73
            $fightsByRound = $this->championship->fightsByRound($numRound)->with('group.parent', 'group.children')->get();
74
            $this->updateParentFight($this->championship, $fightsByRound);
75
        }
76
    }
77
78
79
    /**
80
     * @param Championship $championship
81
     * @param $fightsByRound
82
     */
83
    private function updateParentFight(Championship $championship, $fightsByRound)
84
    {
85
        foreach ($fightsByRound as $fight) {
86
            $parentGroup = $fight->group->parent;
87
            if ($parentGroup == null) break;
88
            $parentFight = $parentGroup->fights->get(0); //TODO This Might change when extending to Preliminary
89
90
            // IN this $fight, is c1 or c2 has the info?
91
            if ($championship->isDirectEliminationType()) {
92
                // determine whether c1 or c2 must be updated
93
                $this->chooseAndUpdateParentFight($fight, $parentFight);
94
            }
95
        }
96
    }
97
98
    /**
99
     * @param $fight
100
     * @param $parentFight
101
     */
102
    private function chooseAndUpdateParentFight($fight, $parentFight)
103
    {
104
        $fighterToUpdate = $fight->getParentFighterToUpdate();
105
        $valueToUpdate = $fight->getValueToUpdate();
106
        // we need to know if the child has empty fighters, is this BYE or undetermined
107
        if ($fight->hasDeterminedParent() && $valueToUpdate != null) {
108
            $parentFight->$fighterToUpdate = $fight->$valueToUpdate;
109
            $parentFight->save();
110
        }
111
    }
112
113
114
    /**
115
     * Returns the parent field that need to be updated
116
     * @return null|string
117
     */
118 View Code Duplication
    public function getParentFighterToUpdate()
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...
119
    {
120
        $childrenGroup = $this->group->parent->children;
0 ignored issues
show
Bug introduced by
The property group does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
121
        foreach ($childrenGroup as $key => $children) {
122
            $childFight = $children->fights->get(0);
123
            if ($childFight->id == $this->id) {
0 ignored issues
show
Bug introduced by
The property id does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
124
                if ($key % 2 == 0) {
125
                    return "c1";
126
                }
127
                if ($key % 2 == 1) {
128
                    return "c2";
129
                }
130
            }
131
        }
132
        return null;
133
    }
134
135
    /**
136
     * In the original fight ( child ) return the field that contains data to copy to parent
137
     * @return null|string
138
     */
139 View Code Duplication
    public function getValueToUpdate()
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
        if ($this->c1 != null && $this->c2 != null) {
0 ignored issues
show
Bug introduced by
The property c1 does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
Bug introduced by
The property c2 does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
142
            return null;
143
        }
144
        if ($this->c1 != null) {
145
            return "c1";
146
        }
147
        if ($this->c2 != null) {
148
            return "c2";
149
        }
150
        return null;
151
    }
152
153
    /**
154
     * Check if we are able to fill the parent fight or not
155
     * If one of the children has c1 x c2, then we must wait to fill parent
156
     *
157
     * @return bool
158
     */
159 View Code Duplication
    public function hasDeterminedParent()
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...
160
    {
161
        if ($this->group->has2Fighters()) return true;
162
        foreach ($this->group->children as $child) {
163
            $fight = $child->fights->get(0);
164
            if ($fight->has2Fighters()) return false;
165
        }
166
        return true;
167
    }
168
169
    /**
170
     * Save Groups with their parent info
171
     * @param integer $numRounds
172
     * @param $numFightersElim
173
     */
174 View Code Duplication
    protected function pushGroups($numRounds, $numFightersElim)
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...
175
    {
176
        for ($roundNumber = 2; $roundNumber <= $numRounds; $roundNumber++) {
177
            // From last match to first match
178
            $maxMatches = ($numFightersElim / pow(2, $roundNumber));
179
180
            for ($matchNumber = 1; $matchNumber <= $maxMatches; $matchNumber++) {
181
                $fighters = $this->createByeGroup(2);
182
                $group = $this->saveGroup(1, $matchNumber, $roundNumber, null);
183
                $this->syncGroup($group, $fighters);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Xoco70\KendoTournaments\...irectEliminationTreeGen as the method syncGroup() does only exist in the following sub-classes of Xoco70\KendoTournaments\...irectEliminationTreeGen: Xoco70\KendoTournaments\...nationCompetitorTreeGen, Xoco70\KendoTournaments\...tEliminationTeamTreeGen. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
184
            }
185
        }
186
    }
187
188
    /**
189
     * Return number of rounds for the tree based on fighter count
190
     * @param $numFighters
191
     * @return int
192
     */
193
    public function getNumRounds($numFighters){
194
        return intval(log($numFighters, 2));
195
    }
196
}
197