WordList.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace AppBundle\Game;
  3. use AppBundle\Game\Exception\RuntimeException;
  4. use AppBundle\Game\Loader\LoaderInterface;
  5. class WordList
  6. {
  7. private $words = [];
  8. private $loaders = [];
  9. private $loaded = false;
  10. private $dictionaries;
  11. public function __construct(array $dictionaries)
  12. {
  13. $this->dictionaries = $dictionaries;
  14. }
  15. public function addLoader(LoaderInterface $loader): void
  16. {
  17. $this->loaders[strtolower($loader->getType())] = $loader;
  18. $this->loaded = false;
  19. }
  20. /**
  21. * Returns a word picked randomly from the loaded dictionaries.
  22. */
  23. public function getRandomWord(): string
  24. {
  25. $this->loadDictionaries();
  26. return $this->words[array_rand($this->words)];
  27. }
  28. /**
  29. * Adds a new word to the list.
  30. */
  31. public function addWord(string $word): void
  32. {
  33. if (!in_array($word, $this->words, true)) {
  34. $this->words[] = $word;
  35. }
  36. }
  37. private function loadDictionaries(): void
  38. {
  39. if ($this->loaded) {
  40. return;
  41. }
  42. foreach ($this->dictionaries as $dictionary) {
  43. $this->loadDictionary($dictionary);
  44. }
  45. $this->loaded = true;
  46. }
  47. private function findLoader(string $type): LoaderInterface
  48. {
  49. $key = strtolower($type);
  50. if (!isset($this->loaders[$key])) {
  51. throw new RuntimeException(sprintf('There is no loader able to load a %s dictionary.', $type));
  52. }
  53. return $this->loaders[$key];
  54. }
  55. private function loadDictionary(string $path): void
  56. {
  57. $loader = $this->findLoader(pathinfo($path, PATHINFO_EXTENSION));
  58. $words = $loader->load($path);
  59. foreach ($words as $word) {
  60. $this->addWord($word);
  61. }
  62. }
  63. }