3 namespace Drupal\Tests\Traits\Core;
6 * Adds ability to convert a list of parameters into a stack of permutations.
8 trait GeneratePermutationsTrait {
11 * Converts a list of possible parameters into a stack of permutations.
13 * Takes a list of parameters containing possible values, and converts all of
14 * them into a list of items containing every possible permutation.
22 * $permutations = $this->generatePermutations($parameters);
25 * ['one' => 0, 'two' => 2],
26 * ['one' => 1, 'two' => 2],
27 * ['one' => 0, 'two' => 3],
28 * ['one' => 1, 'two' => 3],
32 * @param array $parameters
33 * An associative array of parameters, keyed by parameter name, and whose
34 * values are arrays of parameter values.
37 * A list of permutations, which is an array of arrays. Each inner array
38 * contains the full list of parameters that have been passed, but with a
41 public static function generatePermutations(array $parameters) {
42 $all_permutations = [[]];
43 foreach ($parameters as $parameter => $values) {
44 $new_permutations = [];
45 // Iterate over all values of the parameter.
46 foreach ($values as $value) {
47 // Iterate over all existing permutations.
48 foreach ($all_permutations as $permutation) {
49 // Add the new parameter value to existing permutations.
50 $new_permutations[] = $permutation + [$parameter => $value];
53 // Replace the old permutations with the new permutations.
54 $all_permutations = $new_permutations;
56 return $all_permutations;