function DevelGenerateBase::randomSentenceOfLength
Same name in other branches
- 4.x devel_generate/src/DevelGenerateBase.php \Drupal\devel_generate\DevelGenerateBase::randomSentenceOfLength()
Generates a random sentence of specific length.
Words are randomly selected with length from 2 up to the optional parameter $max_word_length. The first word is capitalised. No ending period is added.
Parameters
int $sentence_length: The total length of the sentence, including the word-separating spaces.
int $max_word_length: (optional) Maximum length of each word. Defaults to 8.
Return value
string A sentence of the required length.
1 call to DevelGenerateBase::randomSentenceOfLength()
- MenuDevelGenerate::generateMenus in devel_generate/
src/ Plugin/ DevelGenerate/ MenuDevelGenerate.php - Generates new menus.
File
-
devel_generate/
src/ DevelGenerateBase.php, line 232
Class
- DevelGenerateBase
- Provides a base DevelGenerate plugin implementation.
Namespace
Drupal\devel_generateCode
protected function randomSentenceOfLength(int $sentence_length, int $max_word_length = 8) : string {
// Maximum word length cannot be longer than the sentence length.
$max_word_length = min($sentence_length, $max_word_length);
$words = [];
$remainder = $sentence_length;
do {
// If near enough to the end then generate the exact length word to fit.
// Otherwise, the remaining space cannot be filled with one word, so
// choose a random length, short enough for a following word of at least
// minimum length.
$next_word = $remainder <= $max_word_length ? $remainder : mt_rand(2, min($max_word_length, $remainder - 3));
$words[] = $this->getRandom()
->word($next_word);
$remainder = $remainder - $next_word - 1;
} while ($remainder > 0);
return ucfirst(implode(' ', $words));
}