Skip to content

Commit

Permalink
Helper functions to use our custom validators
Browse files Browse the repository at this point in the history
  • Loading branch information
Nyholm committed Dec 19, 2020
1 parent ab3f536 commit c93487a
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions src/Faker/Generator.php
Expand Up @@ -204,6 +204,55 @@ class Generator
protected $providers = [];
protected $formatters = [];

/**
* @var UniqueGenerator
*/
private $uniqueGenerator;

public function __construct()
{
$this->uniqueGenerator = new UniqueGenerator($this);
}

/**
* With the unique generator you are guaranteed to never get the same two
* values.
*
* @return self The UniqueGenerator is a proxy
*/
public function withUnique()
{
return $this->uniqueGenerator;
}

/**
* Get a value only some percentage of the time.
*
* @param float $weight A probability between 0 and 1, 0 means that we always get the default value.
*
* @return self
*/
public function withMaybe(float $weight = 0.5, $default = null)
{
if (mt_rand(1, 100) <= (100*$weight)) {
return $this;
}

return new DefaultGenerator($default);
}

/**
* To make sure the value meet some criteria, pass a callable that verifies the
* output. If the validator fails, the generator will try again.
*
* @example $faker->withValid(fn($v) => strlen($v) > 3))->name();
* @return self
*/
public function withValid(callable $validator, int $maxRetries = 10000)
{
return new ValidGenerator($this, $validator, $maxRetries);
}

public function addProvider($provider)
{
array_unshift($this->providers, $provider);
Expand Down

0 comments on commit c93487a

Please sign in to comment.