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 {
|
|
|
|
|
|
|
|
protected $key;
|
|
|
|
|
|
|
|
/**
|
2016-11-29 04:27:58 +05:30
|
|
|
* @return Connection
|
2016-02-14 23:20:10 +05:30
|
|
|
*/
|
|
|
|
public function getRedis() {
|
2016-07-17 21:43:40 +05:30
|
|
|
return Yii::$app->redis;
|
2016-02-14 23:20:10 +05:30
|
|
|
}
|
|
|
|
|
2016-11-29 04:27:58 +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
|
|
|
}
|
|
|
|
|
|
|
|
public function setValue($value) {
|
|
|
|
$this->getRedis()->set($this->key, json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function delete() {
|
2016-11-29 04:27:58 +05:30
|
|
|
$this->getRedis()->del($this->key);
|
2016-02-14 23:20:10 +05:30
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
2016-11-29 04:27:58 +05:30
|
|
|
public function exists() : bool {
|
|
|
|
return (bool)$this->getRedis()->exists($this->key);
|
|
|
|
}
|
|
|
|
|
2016-02-14 23:20:10 +05:30
|
|
|
public function expire($ttl) {
|
2016-11-29 04:27:58 +05:30
|
|
|
$this->getRedis()->expire($this->key, $ttl);
|
2016-02-14 23:20:10 +05:30
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
2016-11-29 04:27:58 +05:30
|
|
|
public function __construct(...$key) {
|
|
|
|
if (empty($key)) {
|
|
|
|
throw new InvalidArgumentException('You must specify at least one key.');
|
|
|
|
}
|
|
|
|
|
|
|
|
$this->key = $this->buildKey($key);
|
|
|
|
}
|
|
|
|
|
2016-02-14 23:20:10 +05:30
|
|
|
private function buildKey(array $parts) {
|
|
|
|
$keyParts = [];
|
|
|
|
foreach($parts as $part) {
|
|
|
|
$keyParts[] = str_replace('_', ':', $part);
|
|
|
|
}
|
|
|
|
|
|
|
|
return implode(':', $keyParts);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|