-
Notifications
You must be signed in to change notification settings - Fork 0
/
fizzbuzz.php
117 lines (99 loc) · 1.89 KB
/
fizzbuzz.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
/**
* Interface Word
*/
interface Word
{
public function word();
}
/**
* Class Fizz
*/
class Fizz implements Word
{
public function word()
{
return 'Fizz';
}
}
/**
* Class Buzz
*/
class Buzz implements Word
{
public function word()
{
return 'Buzz';
}
}
/**
* Class FizzBuzz
*/
class FizzBuzz
{
/**
* @var Fizz
*/
protected $fizz;
/**
* @var Buzz
*/
protected $buzz;
/**
* FizzBuzz constructor.
* @param Fizz $fizz
* @param Buzz $buzz
*/
public function __construct(Fizz $fizz, Buzz $buzz)
{
$this->fizz = $fizz;
$this->buzz = $buzz;
}
/**
* @param int $startInt
* @param int $endInt
* @param int $fizzInt
* @param int $buzzInt
* @return Generator
*/
public function generateFizzBuzz(
int $startInt = 1,
int $endInt = 100,
int $fizzInt = 3,
int $buzzInt = 5
)
{
for ($i = $startInt; $i <= $endInt; $i++) {
$isFizz = $this->isMultiple($i, $fizzInt);
$isBuzz = $this->isMultiple($i, $buzzInt);
if( $isFizz && $isBuzz ){
yield $this->fizz->word() . $this->buzz->word();
continue;
}
if( $isFizz ){
yield $this->fizz->word();
continue;
}
if( $isBuzz ){
yield $this->buzz->word();
continue;
}
yield $i;
}
}
/**
* @param int $value
* @param int $multiple
* @return bool
*/
private function isMultiple(int $value, int $multiple): bool
{
return 0 === $value % $multiple;
}
}
$fizz = new Fizz();
$buzz = new Buzz();
$fizzBuzz = new FizzBuzz($fizz, $buzz);
foreach ($fizzBuzz->generateFizzBuzz() as $value) {
echo $value, PHP_EOL;
}