GeneratePermutationsTrait.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace Drupal\Tests\Traits\Core;
  3. /**
  4. * Adds ability to convert a list of parameters into a stack of permutations.
  5. */
  6. trait GeneratePermutationsTrait {
  7. /**
  8. * Converts a list of possible parameters into a stack of permutations.
  9. *
  10. * Takes a list of parameters containing possible values, and converts all of
  11. * them into a list of items containing every possible permutation.
  12. *
  13. * Example:
  14. * @code
  15. * $parameters = [
  16. * 'one' => [0, 1],
  17. * 'two' => [2, 3],
  18. * ];
  19. * $permutations = $this->generatePermutations($parameters);
  20. * // Result:
  21. * $permutations == [
  22. * ['one' => 0, 'two' => 2],
  23. * ['one' => 1, 'two' => 2],
  24. * ['one' => 0, 'two' => 3],
  25. * ['one' => 1, 'two' => 3],
  26. * ]
  27. * @endcode
  28. *
  29. * @param array $parameters
  30. * An associative array of parameters, keyed by parameter name, and whose
  31. * values are arrays of parameter values.
  32. *
  33. * @return array[]
  34. * A list of permutations, which is an array of arrays. Each inner array
  35. * contains the full list of parameters that have been passed, but with a
  36. * single value only.
  37. */
  38. public static function generatePermutations(array $parameters) {
  39. $all_permutations = [[]];
  40. foreach ($parameters as $parameter => $values) {
  41. $new_permutations = [];
  42. // Iterate over all values of the parameter.
  43. foreach ($values as $value) {
  44. // Iterate over all existing permutations.
  45. foreach ($all_permutations as $permutation) {
  46. // Add the new parameter value to existing permutations.
  47. $new_permutations[] = $permutation + [$parameter => $value];
  48. }
  49. }
  50. // Replace the old permutations with the new permutations.
  51. $all_permutations = $new_permutations;
  52. }
  53. return $all_permutations;
  54. }
  55. }