Completed
Push — master ( dd5219...8b7513 )
by Michael
04:15
created

TeamMatchesController   B

Complexity

Total Complexity 40

Size/Duplication

Total Lines 299
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
wmc 40
lcom 0
cbo 2
dl 0
loc 299
rs 8.2608
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A index() 0 4 1
A create() 0 4 1
A store() 0 4 1
F show() 0 107 11
C getTeamNetScore() 0 65 11
D calculatePoints() 0 28 9
A edit() 0 4 1
A update() 0 4 1
A destroy() 0 4 1
A getPointsByYear() 0 10 2

How to fix   Complexity   

Complex Class

Complex classes like TeamMatchesController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use TeamMatchesController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
use GolfLeague\Services\MatchService as MatchService;
4
use GolfLeague\Storage\MatchRound\MatchRoundRepository as MatchRoundRepository;
5
use GolfLeague\Storage\Team\TeamMatchesRepository as TeamMatchesRepository;
6
7
class TeamMatchesController extends \BaseController {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
8
9
    public function __construct(MatchService $match, MatchRoundRepository $matchRoundRepo, TeamMatchesRepository $teamMatchesRepository)
10
    {
11
        $this->match = $match;
12
        $this->matchRoundRepo = $matchRoundRepo;
13
        $this->teamMatchesRepo = $teamMatchesRepository;
14
    }
15
16
    /**
17
	 * Display a listing of the resource.
18
	 *
19
	 * @return Response
20
	 */
21
	public function index()
22
	{
23
		//
24
	}
25
26
27
	/**
28
	 * Show the form for creating a new resource.
29
	 *
30
	 * @return Response
31
	 */
32
	public function create()
33
	{
34
		//
35
	}
36
37
38
	/**
39
	 * Store a newly created resource in storage.
40
	 *
41
	 * @return Response
42
	 */
43
	public function store()
44
	{
45
		//
46
	}
47
48
49
	/**
50
	 * Display the specified resource.
51
	 *
52
	 * @param  int  $id
53
	 * @return Response
54
	 */
55
	public function show($id)
56
	{
57
58
59
        $group = Input::get('group');
60
61
62
        $groupPlayers = $this->matchRoundRepo->matchGroup($id, $group);
63
64
        //Create Player data
65
        $matchUp = array();
66
        foreach($groupPlayers as $key=>$groupPlayer){
67
            $matchUp[$key]['player'] = $groupPlayer->pivot->player_id;
68
            $matchUp[$key]['matchHandicap'] = round($groupPlayer->pivot->handicap ,0);
69
            foreach ($groupPlayer->round as $round){
70
                $matchUp[$key]['team'] = $round->team_id;
71
                $matchUp[$key]['course'] = $round->course_id;
72
                $matchUp[$key]['holescores'] = $round->holescores;
73
            }
74
75
        }
76
77
        // Change lowest handicap to ZERO and change others to reflect it
78
            foreach($matchUp as $key=>$match){
79
                $matchHandicaps[] = $match['matchHandicap'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$matchHandicaps was never initialized. Although not strictly required by PHP, it is generally a good practice to add $matchHandicaps = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
80
            }
81
            $lowestMatchHandicap = min($matchHandicaps);
0 ignored issues
show
Bug introduced by
The variable $matchHandicaps 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...
82
            //handicap change
83
            $handicapChange = $lowestMatchHandicap * -1;
84
            foreach($matchUp as $key=>$match){
85
                $matchUp[$key]['matchHandicap'] = $match['matchHandicap'] + $handicapChange;
86
            }
87
88
        // Separate two teams
89
            $team1 = array(array_shift ($matchUp));
90
            $team1Id = $team1[0]['team'];
91
            $team1Name = Team::select('name')->where('id', '=', $team1Id)->get()->toArray();
92
            foreach($matchUp as $key=>$match){
93
                if($match['team'] == $team1[0]['team']){
94
                    $team1[] = $match;
95
                    unset($matchUp[$key]);
96
                }
97
            }
98
            $team2 = $matchUp;
99
            $team2Id = $team2[1]['team'];
100
            $team2Name = Team::select('name')->where('id', '=', $team2Id)->get()->toArray();
101
102
            $holesData = Hole::select('handicap')->where('course_id', '=', $team1[0]['course'])->get();
103
104
            $team1Scores = $this->getTeamNetScore($team1, $holesData);
105
            //return $team1Scores;
106
            $team2Scores = $this->getTeamNetScore($team2, $holesData);
107
108
            $team1Points = $this->calculatePoints($team1Scores, $team2Scores);
109
            $team2Points = $this->calculatePoints($team2Scores, $team1Scores);
110
111
            //Save Points in Teammatches
112
            Teammatch::where('match_id', '=', $id)->where('team_id', '=', $team1Id)->update(array('pointsWon' => $team1Points));
113
            Teammatch::where('match_id', '=', $id)->where('team_id', '=', $team2Id)->update(array('pointsWon' => $team2Points));
114
115
116
        //Need to determine if same amount of scores are in both
117
        // If not then do not return
118
119
            foreach($team1Scores as $key=>$teamScore){
120
                if($teamScore <= 0){
121
                    $team1Scores[$key] = '';
122
                }
123
            }
124
125
        foreach($team2Scores as $key=>$teamScore){
126
            if($teamScore <= 0){
127
                $team2Scores[$key] = '';
128
            }
129
        }
130
131
        $team[0] = [
0 ignored issues
show
Coding Style Comprehensibility introduced by
$team was never initialized. Although not strictly required by PHP, it is generally a good practice to add $team = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
132
            "team" =>  $team1Name[0]['name'],
133
            "hole1" => $team1Scores[0],
134
            "hole2" => $team1Scores[1],
135
            "hole3" => $team1Scores[2],
136
            "hole4" => $team1Scores[3],
137
            "hole5" => $team1Scores[4],
138
            "hole6" => $team1Scores[5],
139
            "hole7" => $team1Scores[6],
140
            "hole8" => $team1Scores[7],
141
            "hole9" => $team1Scores[8],
142
            "points" =>$team1Points
143
        ];
144
145
        $team[1] = [
146
            "team" =>  $team2Name[0]['name'],
147
            "hole1" => $team2Scores[0],
148
            "hole2" => $team2Scores[1],
149
            "hole3" => $team2Scores[2],
150
            "hole4" => $team2Scores[3],
151
            "hole5" => $team2Scores[4],
152
            "hole6" => $team2Scores[5],
153
            "hole7" => $team2Scores[6],
154
            "hole8" => $team2Scores[7],
155
            "hole9" => $team2Scores[8],
156
            "points" => $team2Points
157
        ];
158
159
        $data['data'] = $team;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
160
        return $data;
161
	}
162
163
    private function getTeamNetScore($team, $holesData)
164
    {
165
        foreach($team as $key=>$item){
166
            // Create holes array for NET
167
            $holes = array();
168
            $i = 1;
169
            foreach($holesData as $key=>$holeData){
170
                $holes[$i] = $holeData->handicap;
171
                $i++;
172
            }
173
174
            // Create stroke array - how many to take away from score
175
            $strokeArray = [
176
                1 => 0,
177
                2 => 0,
178
                3 => 0,
179
                4 => 0,
180
                5 => 0,
181
                6 => 0,
182
                7 => 0,
183
                8 => 0,
184
                9 => 0
185
            ];
186
            //Create array of strokes
187
            for($counter = $item['matchHandicap']; $counter > 0; $counter--){
188
                if($counter > 9){
189
                    $newCounter = $counter - 9;
190
                    while($newCounter > 0) {
191
                        $strokeArray[$newCounter] = $strokeArray[$newCounter] + 1;
192
                        $counter--;
193
                        $newCounter--;
194
                    }
195
                }
196
                $strokeArray[$counter] = $strokeArray[$counter] + 1;
197
            }
198
            // Plus handicaps don't hit previous loop so need its own
199
            //Plus handicap logic
200
201
            foreach($strokeArray as $strokeKey=>$stroke){
202
                $holeKey = array_search($strokeKey,$holes);
203
                $holes[$holeKey] = $stroke;
204
            }
205
206
            ///now have array of strokes to subtract
207
            //get array of holescores
208
209
            $holeScores = $item['holescores'];
210
            foreach($holeScores as $key=>$holeScore){
211
                //check if new score is less PlayerScores
212
                if(isset($playerScores[$key])){ // 2nd time in for hole
213
                    if($playerScores[$key] >= $holeScore['score']){
214
                        $playerScores[$key] = $holeScore['score'] - $holes[$key+1];
215
                    }
216
                } else{ // first time in for hole
217
                    if($holeScore['score'] != null){
218
                        $playerScores[$key] = $holeScore['score'] - $holes[$key+1];
0 ignored issues
show
Bug introduced by
The variable $playerScores 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...
219
                    } else{
220
                        $playerScores[$key] = null;
221
                    }
222
                }
223
            }
224
225
        }
226
        return $playerScores;
227
    }
228
229
    private function calculatePoints($team, $opponent)
230
    {
231
        $points = 0;
232
        $teamTotalScore = 0;
233
        $opponentTotalScore = 0;
234
        foreach ($team as $key=>$score){
235
            if($score != null){
236
                if($score < $opponent[$key]){
237
                    $points++;
238
                }
239
                if($score == $opponent[$key]){
240
                    $points = $points + .5;
241
                }
242
            }
243
            $teamTotalScore = $teamTotalScore + $score;
244
            $opponentTotalScore = $opponentTotalScore + $score;
245
        }
246
        // Bonus point logic
247
        if($team[8] != null && $opponent[8] != null){
248
            if($teamTotalScore > $opponentTotalScore){
249
                $points = $points + 1;
250
            }
251
            if($teamTotalScore = $opponentTotalScore){
0 ignored issues
show
Unused Code introduced by
$teamTotalScore 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...
252
                $points = $points + .5;
253
            }
254
        }
255
        return $points;
256
    }
257
258
	/**
259
	 * Show the form for editing the specified resource.
260
	 *
261
	 * @param  int  $id
262
	 * @return Response
263
	 */
264
	public function edit($id)
265
	{
266
		//
267
	}
268
269
270
	/**
271
	 * Update the specified resource in storage.
272
	 *
273
	 * @param  int  $id
274
	 * @return Response
275
	 */
276
	public function update($id)
277
	{
278
		//
279
	}
280
281
282
	/**
283
	 * Remove the specified resource from storage.
284
	 *
285
	 * @param  int  $id
286
	 * @return Response
287
	 */
288
	public function destroy($id)
289
	{
290
		//
291
	}
292
293
	public function getPointsByYear($year)
294
    {
295
        $teamMatches = Teammatch::select('team_id','pointsWon')->whereYear('created_at', '=', $year)->with('team')->get();
296
        foreach ($teamMatches as $key=>$teamMatch) {
297
            $pointsData[$key]['name'] = $teamMatch['team']['name'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$pointsData was never initialized. Although not strictly required by PHP, it is generally a good practice to add $pointsData = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
298
            $pointsData[$key]['points'] = $teamMatch['pointsWon'];
299
        }
300
        $data['data'] = $pointsData;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
Bug introduced by
The variable $pointsData 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...
301
        return $data;
302
    }
303
304
305
}
306