Created
April 17, 2024 21:22
-
-
Save daverogers/a89671e59bb363a5a4b61e5023b6cc78 to your computer and use it in GitHub Desktop.
uniqueFor Modifier - Faker PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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