resq/src/Service/HubCounter.php
2019-05-14 09:16:15 +00:00

111 lines
2.8 KiB
PHP

<?php
namespace App\Service;
use App\Entity\Hub;
use App\Entity\Rider;
use Doctrine\ORM\EntityManagerInterface;
class HubCounter
{
const RIDER_COUNT_KEY = 'hub.rider';
const JOB_ORDER_KEY = 'hub.jo';
protected $em;
protected $redis;
public function __construct(EntityManagerInterface $em, RedisClientProvider $redis_client)
{
$this->em = $em;
$this->redis = $redis_client->getRedisClient();
}
// get rider key based on id
protected function getRiderKey($hub_id)
{
return self::RIDER_COUNT_KEY . '.' . $hub_id;
}
// get job order key based on id
protected function getJobOrderKey($hub_id)
{
return self::JOB_ORDER_KEY . '.' . $hub_id;
}
// get riders available
public function getAvailableRiderCount($hub_id)
{
$key = $this->getRiderKey($hub_id);
$value = $this->redis->get($key);
if ($value != null)
return $value;
// not in cache
$hub = $this->em->getRepository(Hub::class)->find($hub_id);
$riders = $hub->getActiveRiders();
$rider_count = count($riders);
// store in cache
$this->redis->setnx($key, $rider_count);
return $rider_count;
}
// get job order queue
public function getUnfinishedJobOrderCount($hub_id)
{
$key = $this->getRiderKey($hub_id);
$value = $this->redis->get($key);
if ($value != null)
return $value;
// not in cache
$hub = $em->getRepository(Hub::class)->find($hub_id);
$riders = $hub->getActiveRiders();
$rider_count = count($riders);
// store in cache
$this->redis->setnx($key, $rider_count);
return $rider_count;
}
// add rider available
public function addAvailableRider($hub_id, $count = 1)
{
// cache
$this->getAvailableRiderCount($hub_id);
$key = $this->getRiderKey($hub_id);
$this->redis->incrby($key, $count);
}
// decrease rider available
public function decAvailableRider($hub_id, $count = 1)
{
// cache
$this->getAvailableRiderCount($hub_id);
$key = $this->getRiderKey($hub_id);
$this->redis->decrby($key, $count);
}
// add job order queue
public function addUnfinishedJobOrder($hub_id, $count = 1)
{
// cache
$this->getUnfinishedJobOrderCount($hub_id);
$key = $this->getJobOrderKey($hub_id);
$this->redis->incrby($key, $count);
}
// decrease job order queue
public function decUnfinishedJobOrder($hub_id, $count = 1)
{
// cache
$this->getUnfinishedJobOrderCount($hub_id);
$key = $this->getJobOrderKey($hub_id);
$this->redis->decrby($key, $count);
}
}