Completed
Push — Bowlingkata/Albert ( a8d0e2...ff2053 )
by Albert
02:01
created

Game::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Kata\BowlingKata\Domain;
4
5
final class Game
6
{
7
    const MAX_FRAMES_TO_SCORE = 10;
8
9
    /** @var RollCollection|Roll[] */
10
    private $rolls;
11
12
    /** @var Frame[] */
13
    private $frames;
14
15
    /** @var int */
16
    private $score;
17
18 34
    public function __construct(array $a_roll_array)
19
    {
20 34
        $this->rolls  = new RollCollection($a_roll_array);
21 34
        $this->frames = [new Frame()];
22
23 34
        $this->calculateGameScore();
24 34
    }
25
26 34
    public function score()
27
    {
28 34
        return $this->score;
29
    }
30
31 34
    private function calculateGameScore()
32
    {
33 34
        foreach ($this->rolls as $roll) {
34 34
            $this->calculateRollScore($roll);
35
36 34
            if (count($this->frames) <= self::MAX_FRAMES_TO_SCORE) {
37 34
                $this->score += $roll->score();
38
            }
39
40 34
            $this->addRollToFrame($roll);
41
        }
42 34
    }
43
44 34
    private function addRollToFrame(Roll $roll)
45
    {
46 34
        $current_frame = end($this->frames);
47 34
        $current_frame->addRoll($roll);
48
49 34
        if ($current_frame->isComplete()) {
50 34
            $this->frames[] = new Frame();
51
        }
52 34
    }
53
54 34
    private function calculateRollScore(Roll $roll)
55
    {
56 34
        if ($roll->type()->isDefault() || $roll->type()->isEmpty()) {
57 32
            return;
58
        }
59
60 22
        $current_roll_pointer = key(current($this->rolls));
61 22
        if ($roll->type()->isSpare() && !empty($this->rolls[$current_roll_pointer + 1])) {
62 10
            $roll->increaseScore($this->rolls[$current_roll_pointer + 1]->score());
63
        }
64
65 22
        if ($roll->type()->isStrike() && !empty($this->rolls[$current_roll_pointer + 1])) {
66 14
            $roll->increaseScore($this->rolls[$current_roll_pointer + 1]->score());
67
        }
68
69 22
        if ($roll->type()->isStrike() && !empty($this->rolls[$current_roll_pointer + 2])) {
70 14
            $roll->increaseScore($this->rolls[$current_roll_pointer + 2]->score());
71
        }
72 22
    }
73
}
74