1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace GolfLeague; |
4
|
|
|
|
5
|
|
|
use \Player as Player; |
6
|
|
|
use \Round as Round; |
7
|
|
|
|
8
|
|
|
class Handicap |
9
|
|
|
{ |
10
|
|
|
private $differentialArray; |
11
|
|
|
private $player; |
12
|
|
|
private $roundsUsed; |
13
|
|
|
|
14
|
|
|
public function __construct(Player $player, $roundsUsed = 10) |
15
|
|
|
{ |
16
|
|
|
$this->differentialArray = array(0,1,1,1,1,1,1,2,2,3,3,4,4,5,5,6,6,7,8,9,10); |
17
|
|
|
$this->player = $player; |
18
|
|
|
$this->roundsUsed = $roundsUsed; //20 is USGA standard; Some leagues may want to adjust. |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
public function calculate() |
22
|
|
|
{ |
23
|
|
|
$rounds = Round::where('player_id', '=', $this->player->id)->orderBy('date', 'desc')->take($this->roundsUsed)->get(); |
24
|
|
|
$differential = $this->differential($rounds->count()); |
25
|
|
|
|
26
|
|
|
$i = 1; |
27
|
|
|
foreach ($rounds as $round) { |
28
|
|
|
$differentials[$i] = $round->esc; |
|
|
|
|
29
|
|
|
$i++; |
30
|
|
|
} |
31
|
|
|
sort($differentials); |
32
|
|
|
$chunkedRounds = array_chunk($differentials,$differential,true); |
33
|
|
|
$roundsUsed = $chunkedRounds[0]; |
34
|
|
|
|
35
|
|
|
$sumofDifferentials = array_sum($roundsUsed); |
36
|
|
|
$handicap = (($sumofDifferentials / $differential) * .96) - 36; |
37
|
|
|
$handicap = round($handicap ,2); |
38
|
|
|
|
39
|
|
|
return $handicap; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
// |
43
|
|
|
public function differential($numberOfScores) |
44
|
|
|
{ |
45
|
|
|
if($numberOfScores <= 20){ |
46
|
|
|
return $this->differentialArray[$numberOfScores]; |
47
|
|
|
} else { |
48
|
|
|
return $this->differentialArray[20]; |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
|
53
|
|
|
} |
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:
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 thebar
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.