Skip to content

Instantly share code, notes, and snippets.

@notflip
Created September 24, 2019 18:58
Show Gist options
  • Save notflip/0847f7d44e6546ad3b86e31cd8137ae0 to your computer and use it in GitHub Desktop.
Save notflip/0847f7d44e6546ad3b86e31cd8137ae0 to your computer and use it in GitHub Desktop.
FizzBuzz Solid
<?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