Skip to content

Instantly share code, notes, and snippets.

@daverogers
Created April 17, 2024 21:22
Show Gist options
  • Save daverogers/a89671e59bb363a5a4b61e5023b6cc78 to your computer and use it in GitHub Desktop.
Save daverogers/a89671e59bb363a5a4b61e5023b6cc78 to your computer and use it in GitHub Desktop.
uniqueFor Modifier - Faker PHP
<?php
use Faker\Generator;
use Faker\Provider\Base;
use Faker\UniqueGenerator;
/**
* The default UniqueGenerator groups by the method name called,
* this class allows a custom tag to be specified instead
*
* @mixin Base
*/
class UniqueForGenerator extends UniqueGenerator
{
protected string $tag;
public function __construct(Generator $generator)
{
$this->generator = $generator;
}
public function for(string $tag, int $maxRetries = 10000): self
{
$this->tag = $tag;
$this->maxRetries = $maxRetries;
return $this;
}
public function __call($name, $arguments)
{
if (!isset($this->uniques[$this->tag])) {
$this->uniques[$this->tag] = [];
}
$i = 0;
do {
$res = call_user_func_array(array($this->generator, $name), $arguments);
$i++;
if ($i > $this->maxRetries) {
throw new \OverflowException(sprintf('Maximum retries of %d reached without finding a unique value for tag "%s"', $this->maxRetries, $this->tag));
}
} while (array_key_exists(serialize($res), $this->uniques[$this->tag]));
$this->uniques[$this->tag][serialize($res)] = null;
return $res;
}
}
<?php
use Faker\Provider\Base;
class UniqueForProvider extends Base
{
private ?UniqueForGenerator $uniqueForGenerator = null;
/** Generate unique ID for a given tag name */
public function uniqueFor(string $tag, int $maxRetries = 10000): UniqueForGenerator
{
$generator = $this->uniqueForGenerator ??= new UniqueForGenerator($this->generator);
return $generator->for($tag, $maxRetries);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment