Last active
September 29, 2020 13:33
-
-
Save masacc/ce2f17218547b641a434a7fbe52de458 to your computer and use it in GitHub Desktop.
Nelmio Alice Fixtures Provider : unique constraint on multiple properties
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 | |
// src/Faker/Provider/CombinationsGeneratorProvider.php | |
namespace App\Faker\Provider; | |
use Faker\Provider\Base as BaseProvider; | |
/** | |
* How to use : | |
* - generate a list of random list of all combinations with `<generateAllCombinations()>` | |
* - set the result to a parameter of your fixtures | |
* - get the value of the resource of one of the combinations | |
*/ | |
final class CombinationsGeneratorProvider extends BaseProvider | |
{ | |
/** | |
* @param array ...$datasets | |
* | |
* @return array | |
*/ | |
public function generateAllCombinations(array ...$datasets): array | |
{ | |
$combinations = $this->generateCombinations($datasets); | |
shuffle($combinations); | |
return $combinations; | |
} | |
/** | |
* @param array $datasets | |
* | |
* @return array | |
*/ | |
private function generateCombinations(array $datasets): array | |
{ | |
$datasetA = array_shift($datasets); | |
if (true === empty($datasets)) { | |
return array_map(static function($item) { | |
return [$item]; | |
}, $datasetA); | |
} | |
$combinations = []; | |
foreach ($datasetA as $itemA) { | |
$datasetB = $this->generateCombinations($datasets); | |
foreach ($datasetB as $itemB) { | |
$combinations[] = array_merge([$itemA], $itemB); | |
} | |
} | |
return $combinations; | |
} | |
/** | |
* @param array $combinations | |
* @param int $combinationIndex | |
* @param int $resourceIndex | |
* | |
* @return mixed | |
*/ | |
public function getCombinationValue(array $combinations, int $combinationIndex, int $resourceIndex) | |
{ | |
return $combinations[$combinationIndex][$resourceIndex]; | |
} | |
} |
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
# fixtures/resourceA.yaml | |
stdClass: | |
parameters: | |
uniqueConstraintCombinations: '<generateAllCombinations(@resourceB_{1..12}, @resourceC_{1..4}, @resourceD_{1..35})>' | |
App\Entity\ResourceA: | |
resourceA_{1..50}: | |
name: '<word()>' | |
resourceB: '<getCombinationValue(@parameters->uniqueConstraintCombinations, $current, 0)>' | |
resourceC: '<getCombinationValue(@parameters->uniqueConstraintCombinations, $current, 1)>' | |
resourceD: '<getCombinationValue(@parameters->uniqueConstraintCombinations, $current, 2)>' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment