6e222cb65632ee04079f5fc72fb432d5d5375b13
[yaffs-website] / Core / GeneratePermutationsTrait.php
1 <?php
2
3 namespace Drupal\Tests\Traits\Core;
4
5 /**
6  * Adds ability to convert a list of parameters into a stack of permutations.
7  */
8 trait GeneratePermutationsTrait {
9
10   /**
11    * Converts a list of possible parameters into a stack of permutations.
12    *
13    * Takes a list of parameters containing possible values, and converts all of
14    * them into a list of items containing every possible permutation.
15    *
16    * Example:
17    * @code
18    * $parameters = [
19    *   'one' => [0, 1],
20    *   'two' => [2, 3],
21    * ];
22    * $permutations = $this->generatePermutations($parameters);
23    * // Result:
24    * $permutations == [
25    *   ['one' => 0, 'two' => 2],
26    *   ['one' => 1, 'two' => 2],
27    *   ['one' => 0, 'two' => 3],
28    *   ['one' => 1, 'two' => 3],
29    * ]
30    * @endcode
31    *
32    * @param array $parameters
33    *   An associative array of parameters, keyed by parameter name, and whose
34    *   values are arrays of parameter values.
35    *
36    * @return array[]
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
39    *   single value only.
40    */
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];
51         }
52       }
53       // Replace the old permutations with the new permutations.
54       $all_permutations = $new_permutations;
55     }
56     return $all_permutations;
57   }
58
59 }