Skip to content
This repository has been archived by the owner on Oct 19, 2023. It is now read-only.

Commit

Permalink
Fixed uniqueness of fields - closing #25
Browse files Browse the repository at this point in the history
  • Loading branch information
peterjaap committed Oct 3, 2018
1 parent 1be7bdd commit 2cff18e
Showing 1 changed file with 19 additions and 10 deletions.
29 changes: 19 additions & 10 deletions src/Elgentos/Masquerade/Console/RunCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ class RunCommand extends Command
*/
protected $configHelper;

/**
* @var array
*/
protected $fakerInstanceCache;

/**
*
*/
Expand Down Expand Up @@ -169,7 +174,14 @@ private function fakeData(array $table) : void
}

try {
$updates[$columnName] = $this->getFakerInstance($columnData, $providerClassName)->{$formatter}(...$options);
$fakerInstance = $this->getFakerInstance($columnData, $providerClassName);
if (array_get($columnData, 'unique', false)) {
$updates[$columnName] = $fakerInstance->unique()->{$formatter}(...$options);
} elseif(array_get($columnData, 'optional', false)) {
$updates[$columnName] = $fakerInstance->optional()->{$formatter}(...$options);
} else {
$updates[$columnName] = $fakerInstance->{$formatter}(...$options);
}
} catch (\InvalidArgumentException $e) {
// If InvalidArgumentException is thrown, formatter is not found, use null instead
$updates[$columnName] = null;
Expand Down Expand Up @@ -252,6 +264,11 @@ private function setup()
*/
private function getFakerInstance(array $columnData, $providerClassName = false) : Generator
{
$key = md5(serialize($columnData) . $providerClassName);
if (isset($this->fakerInstanceCache[$key])) {
return $this->fakerInstanceCache[$key];
}

$fakerInstance = FakerFactory::create($this->locale);

$provider = false;
Expand All @@ -266,15 +283,7 @@ private function getFakerInstance(array $columnData, $providerClassName = false)
$fakerInstance->addProvider($provider);
}

if (array_get($columnData, 'unique', false)) {
$fakerInstance->unique();
}
if (array_get($columnData, 'optional', false)) {
$fakerInstance->optional();
}
if (array_get($columnData, 'valid', false)) {
$fakerInstance->valid();
}
$this->fakerInstanceCache[$key] = $fakerInstance;

return $fakerInstance;
}
Expand Down

0 comments on commit 2cff18e

Please sign in to comment.