Skip to content

Instantly share code, notes, and snippets.

@masacc
Last active September 29, 2020 13:33
Show Gist options
  • Save masacc/ce2f17218547b641a434a7fbe52de458 to your computer and use it in GitHub Desktop.
Save masacc/ce2f17218547b641a434a7fbe52de458 to your computer and use it in GitHub Desktop.
Nelmio Alice Fixtures Provider : unique constraint on multiple properties
<?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];
}
}
# 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