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