2019-09-23 03:23:13 +05:30
|
|
|
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
namespace common\tests\_support\Redis;
|
|
|
|
|
|
|
|
use InvalidArgumentException;
|
|
|
|
use yii\base\ArrayAccessTrait;
|
|
|
|
use yii\di\Instance;
|
|
|
|
use yii\helpers\ArrayHelper;
|
|
|
|
use yii\helpers\Json;
|
|
|
|
use yii\redis\Connection;
|
|
|
|
use yii\test\FileFixtureTrait;
|
|
|
|
use yii\test\Fixture as BaseFixture;
|
|
|
|
|
|
|
|
class Fixture extends BaseFixture {
|
|
|
|
use ArrayAccessTrait;
|
|
|
|
use FileFixtureTrait;
|
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
public string|Connection $redis = 'redis';
|
2019-09-23 03:23:13 +05:30
|
|
|
|
|
|
|
public $keysPrefix = '';
|
|
|
|
|
|
|
|
public $keysPostfix = '';
|
|
|
|
|
|
|
|
public $data = [];
|
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
public function init(): void {
|
2019-09-23 03:23:13 +05:30
|
|
|
parent::init();
|
|
|
|
$this->redis = Instance::ensure($this->redis, Connection::class);
|
|
|
|
}
|
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
public function load(): void {
|
2019-09-23 03:23:13 +05:30
|
|
|
$this->data = [];
|
|
|
|
foreach ($this->getData() as $key => $data) {
|
|
|
|
$key = $this->buildKey($key);
|
|
|
|
$preparedData = $this->prepareData($data);
|
|
|
|
if (is_array($preparedData)) {
|
|
|
|
$this->redis->sadd($key, ...$preparedData);
|
|
|
|
} else {
|
|
|
|
$this->redis->set($key, $preparedData);
|
|
|
|
}
|
|
|
|
|
|
|
|
$this->data[$key] = $data;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
public function unload(): void {
|
2019-09-23 03:23:13 +05:30
|
|
|
$this->redis->flushdb();
|
|
|
|
}
|
|
|
|
|
|
|
|
protected function getData(): array {
|
|
|
|
return $this->loadData($this->dataFile);
|
|
|
|
}
|
|
|
|
|
|
|
|
protected function prepareData($input) {
|
|
|
|
if (is_string($input)) {
|
|
|
|
return $input;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (is_int($input) || is_bool($input)) {
|
|
|
|
return (string)$input;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (is_array($input)) {
|
|
|
|
if (!ArrayHelper::isAssociative($input)) {
|
|
|
|
return $input;
|
|
|
|
}
|
|
|
|
|
|
|
|
return Json::encode($input);
|
|
|
|
}
|
|
|
|
|
|
|
|
throw new InvalidArgumentException('Unsupported input type');
|
|
|
|
}
|
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
protected function buildKey(string|int $key): string {
|
2019-09-23 03:23:13 +05:30
|
|
|
return $this->keysPrefix . $key . $this->keysPostfix;
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|