2016-02-14 23:20:10 +05:30
|
|
|
<?php
|
2016-11-27 20:11:39 +05:30
|
|
|
namespace common\components\Redis;
|
2016-02-14 23:20:10 +05:30
|
|
|
|
|
|
|
use InvalidArgumentException;
|
|
|
|
use Yii;
|
|
|
|
|
|
|
|
class Key {
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
private $key;
|
2016-02-14 23:20:10 +05:30
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
public function __construct(...$key) {
|
|
|
|
if (empty($key)) {
|
|
|
|
throw new InvalidArgumentException('You must specify at least one key.');
|
|
|
|
}
|
|
|
|
|
|
|
|
$this->key = $this->buildKey($key);
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getRedis(): Connection {
|
2016-07-17 21:43:40 +05:30
|
|
|
return Yii::$app->redis;
|
2016-02-14 23:20:10 +05:30
|
|
|
}
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
public function getKey(): string {
|
2016-02-14 23:20:10 +05:30
|
|
|
return $this->key;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getValue() {
|
2016-11-29 04:27:58 +05:30
|
|
|
return $this->getRedis()->get($this->key);
|
2016-02-14 23:20:10 +05:30
|
|
|
}
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
public function setValue($value): self {
|
2016-11-30 04:49:14 +05:30
|
|
|
$this->getRedis()->set($this->key, $value);
|
2018-04-18 02:17:25 +05:30
|
|
|
|
2016-02-14 23:20:10 +05:30
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
public function delete(): self {
|
|
|
|
$this->getRedis()->del([$this->getKey()]);
|
2018-04-18 02:17:25 +05:30
|
|
|
|
2016-02-14 23:20:10 +05:30
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
public function exists(): bool {
|
2016-11-29 04:27:58 +05:30
|
|
|
return (bool)$this->getRedis()->exists($this->key);
|
|
|
|
}
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
public function expire(int $ttl): self {
|
2016-11-29 04:27:58 +05:30
|
|
|
$this->getRedis()->expire($this->key, $ttl);
|
2018-04-18 02:17:25 +05:30
|
|
|
|
2016-02-14 23:20:10 +05:30
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
public function expireAt(int $unixTimestamp): self {
|
2016-11-30 04:49:14 +05:30
|
|
|
$this->getRedis()->expireat($this->key, $unixTimestamp);
|
2018-04-18 02:17:25 +05:30
|
|
|
|
2016-11-30 04:49:14 +05:30
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
private function buildKey(array $parts): string {
|
2016-02-14 23:20:10 +05:30
|
|
|
$keyParts = [];
|
2018-04-18 02:17:25 +05:30
|
|
|
foreach ($parts as $part) {
|
2016-02-14 23:20:10 +05:30
|
|
|
$keyParts[] = str_replace('_', ':', $part);
|
|
|
|
}
|
|
|
|
|
|
|
|
return implode(':', $keyParts);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|