Skip to content

Instantly share code, notes, and snippets.

@casperwilkes
Last active March 25, 2020 17:11
Show Gist options
  • Save casperwilkes/5427aa44c2d3cd48f54e564e7e7c803a to your computer and use it in GitHub Desktop.
Save casperwilkes/5427aa44c2d3cd48f54e564e7e7c803a to your computer and use it in GitHub Desktop.
Different ways to generate faker sentences, paragraphs, and word arrays using native Faker `realText` algorithm.
<?php
use Faker\Generator as Faker;
/**
* Different ways to generate faker sentences, paragraphs, and word arrays using native
* Faker `realText` algorithm.
**/
if (!function_exists('fakerRealParagraph')) {
/**
* Generates real text paragraphs from faker realtext algorithm
* @param Faker $faker Faker instance
* @param int $min Minimum amount of paragraphs
* @param int $max Maximum number of paragraphs
* @param int $tmin Character tolerance minimum
* @param int $tmax Character tolerance maximum
* @return string A string of text containing paragraphs, separated by new lines
*/
function fakerRealParagraphs(Faker $faker, int $min = 1, int $max = 5, int $tmin = 100, int $tmax = 500) {
// Grab random number between min and max //
$num = $faker->numberBetween($min, $max);
$paragraphs = [];
// Loop through num //
for ($i = 0; $i < $num; $i++) {
// Grab real text using tolerance min and max //
$paragraphs[] = trim($faker->realText($faker->numberBetween($tmin, $tmax)));
}
// Return a string containing all the paragraphs, separated by newlines //
return implode(PHP_EOL . PHP_EOL, $paragraphs);
}
}
if (!function_exists('fakerRealWords')) {
/**
* Returns an array of words based on realText algorithm
* @param Faker $faker Faker instance
* @param int $min Minimum character tolerance
* @param int $max Maximum character tolerance
* @param bool $strip Strip punctuation
* @return array
* @uses fakerRealSentence
*/
function fakerRealWords(Faker $faker, int $min = 10, $max = 100, bool $strip = true): array {
// Use real sentence to grab a sentence of random words //
$text = fakerRealSentence($faker, $min, $max, $strip);
return explode(' ', $text);
}
}
if (!function_exists('fakerRealSentence')) {
/**
* Generates a real text sentence
* @param Faker $faker Faker instance
* @param int $min Minimum amount of chars
* @param int $max Maximum amount of chars
* @param bool $strip Strips punctuation from text
* @return string
*/
function fakerRealSentence(Faker $faker, int $min = 25, int $max = 100, bool $strip = true): string {
// Get a string of text between min and max length //
$text = $faker->realText($faker->numberBetween($min, $max));
// Strip out punctuation //
if ($strip) {
$text = preg_replace('#[[:punct:]]#', '', $text);
}
return trim($text);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment