Last active
January 25, 2018 23:19
-
-
Save vhorky/1f6c2e0c9199e37f853182d8ecd99fb4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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