|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Ingenerator\PHPUtils\Random; |
| 4 | + |
| 5 | +use InvalidArgumentException; |
| 6 | +use function array_filter; |
| 7 | +use function array_values; |
| 8 | +use function crc32; |
| 9 | +use function implode; |
| 10 | +use function mt_rand; |
| 11 | +use function mt_srand; |
| 12 | +use function preg_split; |
| 13 | + |
| 14 | +class ConsistentStringScrambler |
| 15 | +{ |
| 16 | + /** |
| 17 | + * Consistently "randomise" the words in a string to be the same for the same random seed value |
| 18 | + */ |
| 19 | + public function shuffleWords(?string $input, string $random_seed): ?string |
| 20 | + { |
| 21 | + if (empty($random_seed)) { |
| 22 | + throw new InvalidArgumentException('No seed value provided to '.__METHOD__); |
| 23 | + } |
| 24 | + |
| 25 | + // Break the string into words (and return null if there is no content / only whitespace) |
| 26 | + $words = array_filter(preg_split('/\s+/', $input ?? '')); |
| 27 | + |
| 28 | + if (empty($words)) { |
| 29 | + return NULL; |
| 30 | + } |
| 31 | + |
| 32 | + |
| 33 | + // Convert the arbitrary seed input into an integer suitable for seeding the PRNG - doesn't |
| 34 | + // need to be complex, just enough to give the randomness a bit of variety |
| 35 | + $seed = crc32($random_seed); |
| 36 | + |
| 37 | + return implode(' ', $this->seededShuffle($words, $seed)); |
| 38 | + |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * Seeded Fisher-Yates shuffle implemented as per https://stackoverflow.com/a/19658344 |
| 43 | + */ |
| 44 | + private function seededShuffle(array $items, int $seed): array |
| 45 | + { |
| 46 | + mt_srand($seed); |
| 47 | + // Ensure the array is 0-indexed |
| 48 | + $items = array_values($items); |
| 49 | + |
| 50 | + try { |
| 51 | + |
| 52 | + for ($i = count($items) - 1; $i > 0; $i--) { |
| 53 | + // Swap each item with an item from a random position (which may mean some values |
| 54 | + // are swapped more than once). |
| 55 | + $rnd = mt_rand(0, $i); |
| 56 | + $old_item_i = $items[$i]; |
| 57 | + $items[$i] = $items[$rnd]; |
| 58 | + $items[$rnd] = $old_item_i; |
| 59 | + } |
| 60 | + |
| 61 | + return $items; |
| 62 | + } finally { |
| 63 | + // Reset the random seed to be random again so that this does not impact on later |
| 64 | + // random numbers from elsewhere in the app. |
| 65 | + mt_srand(); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments