Reputation: 3692
I'm working with this library, and I've encountered a problem I have failed to solve.
I like some fields with limit size, such userName (Faker\Provider\Internet). I think ot's not good idea use string with 255 for this field and like limit to 15.
After some crash on seed generation for my table i read code.
protected static $userNameFormats = array(
'{{lastName}}.{{firstName}}',
'{{firstName}}.{{lastName}}',
'{{firstName}}##',
'?{{lastName}}',
);
public function userName()
{
$format = static::randomElement(static::$userNameFormats);
$username = static::bothify($this->generator->parse($format));
return strtolower(static::transliterate($username));
}
For use with my program, i think create a fork. On this fork modify code
protected static $userNickFormats = array(
'{{firstName}}',
'{{firstName}}#',
'{{firstName}}##',
'{{firstName}}###',
'?{{lastName}}##',
);
public function userNick($limit = 15)
{
$format = static::randomElement(static::$userNickFormats);
$username = static::bothify($this->generator->parse($format));
while (strlen($username) > $limit) {
$username = static::bothify($this->generator->parse($format));
}
return strtolower(static::transliterate($username));
}
I think there is a best way for this.
Upvotes: 2
Views: 1406
Reputation: 513
I'm not sure a fork of Faker is the easiest way to go about this.
Consider just creating your own Provider class and add it to faker. See the documentation.
In your case it might look something like this (code blatantly copied from the docs):
userNickProvider.php
<?php
class UserNick extends \Faker\Provider\Base
{
protected static $userNickFormats = array(
'{{firstName}}',
'{{firstName}}#',
'{{firstName}}##',
'{{firstName}}###',
'?{{lastName}}##',
);
public function userNick()
{
$format = static::randomElement(static::$userNickFormats);
$username = static::bothify($this->generator->parse($format));
return strtolower(static::transliterate($username));
}
}
As for the limit you need, there is a modifier called valid()
you can use with any of the faker methods. You just supply a function that returns a bool deciding if the generated value is a valid one, otherwise it generates another and so on. So you don't have to do this in your provider function.
First the validator:
$max15 = function($string) {
return mb_strlen($string) <= 15;
};
Then you can use it like this:
$faker = new Faker\Generator();
$faker->addProvider(new UserNick($faker));
$name = $faker->valid($max15)->userNick;
In summary:
You don't have to fork Faker to get what you want, just write your own Provider.
Upvotes: 2