1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Utility class for shuffling information. |
5
|
|
|
*/ |
6
|
|
|
|
7
|
|
|
namespace CryptoManana\Utilities; |
8
|
|
|
|
9
|
|
|
use \CryptoManana\Core\Abstractions\Containers\AbstractRandomnessInjectable as RandomnessContainer; |
10
|
|
|
use \CryptoManana\Core\Interfaces\Randomness\DataShufflingInterface as Shuffling; |
11
|
|
|
use \CryptoManana\Core\StringBuilder as StringBuilder; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Class DataShuffler - Utility class for data shuffling. |
15
|
|
|
* |
16
|
|
|
* @package CryptoManana\Utilities |
17
|
|
|
*/ |
18
|
|
|
class DataShuffler extends RandomnessContainer implements Shuffling |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* Shuffle a string. |
22
|
|
|
* |
23
|
|
|
* @param string $string The string for shuffling. |
24
|
|
|
* |
25
|
|
|
* @return string The output shuffled/scrambled string. |
26
|
|
|
*/ |
27
|
|
|
public function shuffleString($string = '') |
28
|
|
|
{ |
29
|
|
|
// Validate input |
30
|
|
|
if (!is_string($string)) { |
|
|
|
|
31
|
|
|
throw new \InvalidArgumentException('The supplied argument is not of type string.'); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
if (empty($string)) { |
35
|
|
|
return $string; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
// Convert the string to an array |
39
|
|
|
$array = StringBuilder::stringSplit($string, 1); |
40
|
|
|
|
41
|
|
|
// Reuse the code for array shuffling and convert result to string |
42
|
|
|
return implode('', static::shuffleArray($array)); |
|
|
|
|
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Shuffle an array. |
47
|
|
|
* |
48
|
|
|
* @param array $array The array for shuffling. |
49
|
|
|
* |
50
|
|
|
* @return array The output shuffled/scrambled array. |
51
|
|
|
*/ |
52
|
|
|
public function shuffleArray(array $array = []) |
53
|
|
|
{ |
54
|
|
|
// Validate input |
55
|
|
|
if (empty($array)) { |
56
|
|
|
return $array; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
$shuffled = []; |
60
|
|
|
$iterator = 0; |
61
|
|
|
|
62
|
|
|
// Reset pointer to the begging |
63
|
|
|
reset($array); |
64
|
|
|
|
65
|
|
|
// Iterate through array elements |
66
|
|
|
foreach ($array as $keyName => $value) { |
67
|
|
|
// Choose random index |
68
|
|
|
$newIndex = ($iterator === 0) ? 0 : $this->randomnessSource->getInt(0, $iterator); |
|
|
|
|
69
|
|
|
|
70
|
|
|
// Shuffling logic |
71
|
|
|
if ($newIndex === $iterator) { |
72
|
|
|
$shuffled[] = $value; |
73
|
|
|
} else { |
74
|
|
|
$shuffled[] = $shuffled[$newIndex]; |
75
|
|
|
$shuffled[$newIndex] = $value; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
// Update the index |
79
|
|
|
$iterator++; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
// Return the shuffled array |
83
|
|
|
return $shuffled; |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|