Skip to content

Instantly share code, notes, and snippets.

@vhorky
Last active January 25, 2018 23:19
Show Gist options
  • Save vhorky/1f6c2e0c9199e37f853182d8ecd99fb4 to your computer and use it in GitHub Desktop.
Save vhorky/1f6c2e0c9199e37f853182d8ecd99fb4 to your computer and use it in GitHub Desktop.
<?php declare(strict_types=1);
final class ServerResolver
{
private const CONFIG = [
'free_space' => 500,
'tcp_connection' => 300,
'upload_speed' => 200,
'download_speed' => 200,
];
/**
* @return StorageServer|null
*/
public function findBestUploadServer()
{
$servers = $this->getOnlineServers();
foreach (self::CONFIG as $field => $points) {
$this->updateAvailabilityIndex($servers, $field, $points);
}
return $servers[0];
}
private function updateAvailabilityIndex(array &$servers, string $field, int $points)
{
usort($servers, function ($a, $b, $field) {
return $b[$field] <=> $a[$field];
});
foreach ($servers as $key => $server) {
$currIndex = $servers[$key]['availabilityIndex'] ?? 0;
$servers[$key]['availabilityIndex'] = $currIndex + ($points / ($key + 2));
}
}
private function getOnlineServers(): array
{
/** @var StorageServer[] $servers */
$servers = StorageServer::find(['online = 1']);
if (count($servers) === 0) {
throw new LogicException('No servers available');
}
return $servers->toArray();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment