Skip to content

Commit

Permalink
refactor: extract randomizer logic
Browse files Browse the repository at this point in the history
  • Loading branch information
gere-lajos committed Apr 19, 2024
1 parent 974b199 commit d0e951b
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 21 deletions.
28 changes: 7 additions & 21 deletions src/Meow.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,28 +16,28 @@ public function __construct(
public function name(int $count = 1): string|array
{
if($count === 1) {
return $this->pickRandom($this->dictionary->names());
return Randomizer::pick($this->dictionary->names());
}

return $this->pickRandomToArray(fn () => $this->name(), $count);
return Randomizer::pickToArray(fn () => $this->name(), $count);
}

public function word(int $count = 1): string|array
{
if($count === 1) {
return $this->pickRandom($this->dictionary->words());
return Randomizer::pick($this->dictionary->words());
}

return $this->pickRandomToArray(fn () => $this->word(), $count);
return Randomizer::pickToArray(fn () => $this->word(), $count);
}

public function sentence(int $count = 1, int $minWords = Config::MIN_WORDS, int $maxWords = Config::MAX_WORDS): string|array
{
if($count === 1) {
return ucfirst(implode(' ', $this->words(mt_rand($minWords, $maxWords)))) . '.';
return ucfirst(implode(' ', $this->word(mt_rand($minWords, $maxWords)))) . '.';
}

return $this->pickRandomToArray(fn () => $this->sentence(), $count);
return Randomizer::pickToArray(fn () => $this->sentence(), $count);
}

public function paragraph(int $count = 1, int $minSentences = Config::MIN_SENTENCES, int $maxSentences = Config::MAX_SENTENCES): string|array
Expand All @@ -46,20 +46,6 @@ public function paragraph(int $count = 1, int $minSentences = Config::MIN_SENTEN
return implode(' ', $this->sentence(mt_rand($minSentences, $maxSentences)));
}

return $this->pickRandomToArray(fn () => $this->paragraph(), $count);
}

private function pickRandom(array $options): string
{
return $options[array_rand($options)];
}

private function pickRandomToArray(callable $callback, int $count): array
{
$items = [];
for ($i = 0; $i < $count; $i++) {
$items[] = $callback();
}
return $items;
return Randomizer::pickToArray(fn () => $this->paragraph(), $count);
}
}
23 changes: 23 additions & 0 deletions src/Randomizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

namespace GereLajos\MeowMaker;

class Randomizer
{
public static function pick(array $options): string
{
return $options[array_rand($options)];
}

public static function pickToArray(callable $callback, int $count): array
{
$items = [];
for ($i = 0; $i < $count; $i++) {
$items[] = $callback();
}

return $items;
}
}

0 comments on commit d0e951b

Please sign in to comment.