resq/src/Service/JobOrderCache.php

132 lines
3.3 KiB
PHP

<?php
namespace App\Service;
use App\Service\RedisClientProvider;
use App\Entity\JobOrder;
class JobOrderCache
{
protected $redis;
protected $active_jo_key;
protected $latest_active_jo_key;
public function __construct(RedisClientProvider $redis_prov, $active_jo_key,
$latest_jo_key)
{
$this->redis = $redis_prov->getRedisClient();
$this->active_jo_key = $active_jo_key;
$this->latest_active_jo_key = $latest_jo_key;
}
public function addActiveJobOrder(JobOrder $jo)
{
$coords = $jo->getCoordinates();
$this->redis->geoadd(
$this->active_jo_key,
$coords->getLongitude(),
$coords->getLatitude(),
$jo->getID()
);
}
public function addLatestActiveJoborder(JobOrder $jo)
{
$coords = $jo->getCoordinates();
// add to JO cache with expiry date
$key = $jo->getID();
$data = [
'id' => $key,
'latitude' => $coords->getLatitude(),
'longitude' => $coords->getLongitude(),
];
$value = json_encode($data);
$this->redis->hset($this->latest_active_jo_key, $key, $value);
}
public function getAllActiveJobOrders()
{
$all_jo = $this->redis->georadius(
$this->active_jo_key,
0,
0,
41000,
'km',
['WITHCOORD' => true]
);
$jo_locs = [];
foreach ($all_jo as $jo_data)
{
$id = $jo_data[0];
$lng = $jo_data[1][0];
$lat = $jo_data[1][1];
$jo_locs[$id] = [
'longitude' => $lng,
'latitude' => $lat,
];
}
// error_log(print_r($all_jo, true));
return $jo_locs;
}
public function getAllLatestActiveJobOrders()
{
// get all fields in latest_active_jo hash
$latest_active_jos = $this->redis->hgetall($this->latest_active_jo_key);
$jo_locations = [];
foreach ($latest_active_jos as $active_jo)
{
$jo_data = json_decode($active_jo, true);
$id = '';
$lat = '';
$lng = '';
foreach ($jo_data as $key => $value)
{
if ($key == 'id')
$id = $value;
if ($key == 'longitude')
$lng = $value;
if ($key == 'latitude')
$lat = $value;
}
$jo_locations[$id] = [
'longitude' => $lng,
'latitude' => $lat,
];
}
//error_log(print_r($jo_locations, true));
return $jo_locations;
}
public function removeActiveJobOrder(JobOrder $jo)
{
$this->redis->zrem(
$this->active_jo_key,
$jo->getID()
);
}
public function removeLatestActiveJobOrder(JobOrder $jo)
{
// remove key from latest active jo
$this->redis->hdel($this->latest_active_jo_key, $jo->getID());
}
public function clearLatestActiveJobOrderCache()
{
$keys = $this->redis->hkeys($this->latest_active_jo_key);
foreach ($keys as $key)
{
$this->redis->hdel($this->latest_active_jo_key, $key);
}
}
}