Skip to content

Commit 7acd49d

Browse files
committed
feat(config): add array shuffling on instantiation
1 parent 37fb133 commit 7acd49d

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/Lib/Configuration.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,11 @@ class Configuration
6666
*/
6767
private int $logLevel;
6868

69+
/**
70+
* @var bool
71+
*/
72+
private bool $randomizeNodes;
73+
6974
/**
7075
* Configuration constructor.
7176
*
@@ -83,6 +88,11 @@ public function __construct(array $config)
8388
$this->nodes[] = new Node($node['host'], $node['port'], $node['path'] ?? '', $node['protocol']);
8489
}
8590

91+
$this->randomizeNodes = $config['randomize_nodes'] ?? true;
92+
if ($this->randomizeNodes) {
93+
$this->shuffleNodes();
94+
}
95+
8696
$nearestNode = $config['nearest_node'] ?? null;
8797
$this->nearestNode = null;
8898
if (null !== $nearestNode) {
@@ -237,4 +247,18 @@ public function getClient(): ClientInterface | HttpMethodsClient
237247
}
238248
return $this->client;
239249
}
250+
251+
/**
252+
* Shuffles the nodes array using Fisher-Yates algorithm
253+
*/
254+
private function shuffleNodes(): void
255+
{
256+
$count = count($this->nodes);
257+
for ($i = $count - 1; $i > 0; $i--) {
258+
$j = random_int(0, $i);
259+
$temp = $this->nodes[$i];
260+
$this->nodes[$i] = $this->nodes[$j];
261+
$this->nodes[$j] = $temp;
262+
}
263+
}
240264
}

0 commit comments

Comments
 (0)