Created
September 24, 2019 18:58
-
-
Save notflip/0847f7d44e6546ad3b86e31cd8137ae0 to your computer and use it in GitHub Desktop.
FizzBuzz Solid
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
interface rule | |
{ | |
public function validates(int $number): bool; | |
public function replace(): string; | |
} | |
class IsEvenRule implements Rule | |
{ | |
public function validates($number): bool | |
{ | |
return $number % 2 === 0; | |
} | |
public function replace(): string | |
{ | |
return 'Whizz'; | |
} | |
} | |
class FizzBuzz | |
{ | |
private $rules; | |
public function addRule(Rule $rule) | |
{ | |
$this->rules[] = $rule; | |
} | |
public function generateList(int $number): array | |
{ | |
$list = []; | |
for($i = 0; $i < $number; $i++) | |
{ | |
$list[] = $this->generateElement($i); | |
} | |
return $list; | |
} | |
public function generateElement(int $number) | |
{ | |
foreach($this->rules as $rule) { | |
if ($rule->validates($number)) { | |
return $rule->replace(); | |
} | |
return (string) $number; | |
} | |
} | |
} | |
$fizzbuzz = new FizzBuzz(); | |
$fizzbuzz->addRule(new IsEvenRule()); | |
print_r($fizzbuzz->generateList(100)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment