resq/src/Service/HubDistributor.php
2021-10-08 12:34:55 +00:00

118 lines
3.2 KiB
PHP

<?php
namespace App\Service;
use App\Service\RedisClientProvider;
use App\Entity\Hub;
class HubDistributor
{
protected $redis;
protected $hub_jo_key;
public function __construct(RedisClientProvider $redis, $hub_jo_key)
{
$this->redis = $redis->getRedisClient();
$this->hub_jo_key = $hub_jo_key;
}
public function incrementJoCountForHub(Hub $hub)
{
$key = $hub->getID();
// get current count
$jo_count = $this->redis->hget($this->hub_jo_key, $key);
if ($jo_count == false)
{
// hub not in hash
// add hub to hash
// set to 1 since this is first jo for hub
$this->redis->hset($this->hub_jo_key, $key, 1);
}
else
{
// hub exist in hash
// add to count
$this->redis->hset($this->hub_jo_key, $key, $jo_count + 1);
}
}
public function decrementJoCountForHub(Hub $hub)
{
$key = $hub->getID();
// get current count
$jo_count = $this->redis->hget($this->hub_jo_key, $key);
if ($jo_count)
{
// hub exist in hash
// decrement count
$this->redis->hset($this->hub_jo_key, $key, $jo_count - 1);
}
}
public function arrangeHubs($hubs)
{
if (count($hubs) == 1)
return $hubs;
$arranged_hubs = [];
foreach ($hubs as $hub_data)
{
$hub = $hub_data['hub'];
// need the id of hub
$key = $hub->getID();
// get jo count of hub
$hub_jo_count = $this->redis->hget($this->hub_jo_key, $key);
// check if hub is in hash. if not, hub has no jobs
// but should still be added to results
// TODO: rename the jo_count key so that it won't collide
// later on with the dispatch JO page.
if ($hub_jo_count != null)
{
$arranged_hubs[] = [
'hub' => $hub,
'db_distance' => $hub_data['db_distance'],
'distance' => $hub_data['distance'],
'duration' => $hub_data['duration'],
'jo_count' => $hub_jo_count,
];
}
else
{
$arranged_hubs[] = [
'hub' => $hub,
'db_distance' => $hub_data['db_distance'],
'distance' => $hub_data['distance'],
'duration' => $hub_data['duration'],
'jo_count' => 0,
];
}
}
usort($arranged_hubs, function($a, $b) {
if ($a['jo_count'] == $b['jo_count'])
{
if ($a['distance'] == $b['distance'])
return 0;
if ($a['distance'] < $b['distance'])
return -1;
return 1;
}
if ($a['jo_count'] < $b['jo_count'])
return -1;
else
return 1;
});
// error_log('arranged hubs ' . json_encode($arranged_hubs));
return $arranged_hubs;
}
}