-
Notifications
You must be signed in to change notification settings - Fork 0
/
DictionaryFile.php
62 lines (55 loc) · 1.39 KB
/
DictionaryFile.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
<?php
namespace GregorJ\CorrectHorse\Dictionaries;
use Exception;
use GregorJ\CorrectHorse\DictionaryInterface;
use RuntimeException;
use function count;
use function dirname;
use function file;
use function file_exists;
use function random_int;
use function trim;
/**
* Class DictionaryFile
*/
final class DictionaryFile implements DictionaryInterface
{
/**
* Constants defining the files in the dictionary directory.
*/
protected const DICT_DIR = 'dict';
/**
* @var string
*/
private $filename;
/**
* Initialize the dictionary with a filename from the dict/ subdirectory.
* @param string $filename
* @throws RuntimeException
*/
public function __construct(string $filename)
{
$this->filename = dirname(__DIR__, 2)
. DIRECTORY_SEPARATOR
. self::DICT_DIR
. DIRECTORY_SEPARATOR
. $filename;
if (!file_exists($this->filename)) {
throw new RuntimeException('File not found: ' . $this->filename);
}
}
/**
* Get a random word from the dictionary.
* @return string
* @throws Exception
*/
public function getRandomWord(): string
{
$lines = file($this->filename);
$max = count($lines) - 1;
do {
$line = trim($lines[random_int(0, $max)]);
} while ($line === '');
return $line;
}
}