MadelineProto/src/danog/MadelineProto/Db/MemoryArray.php

87 lines
2.2 KiB
PHP
Raw Normal View History

2020-04-25 21:57:55 +02:00
<?php
namespace danog\MadelineProto\Db;
2020-04-28 02:41:06 +02:00
use Amp\Producer;
use Amp\Promise;
use Amp\Success;
use danog\MadelineProto\Logger;
use danog\MadelineProto\Settings\Database\Memory;
2020-04-28 02:41:06 +02:00
use function Amp\call;
/**
* Memory database backend.
*/
2020-04-27 02:21:18 +02:00
class MemoryArray extends \ArrayIterator implements DbArray
2020-04-25 21:57:55 +02:00
{
2020-04-27 02:21:18 +02:00
protected function __construct($array = [], $flags = 0)
{
parent::__construct((array) $array, $flags | self::STD_PROP_LIST);
}
2020-04-25 21:57:55 +02:00
/**
* Get instance.
*
* @param string $table
2020-10-23 18:19:20 +02:00
* @param mixed $previous
* @param Memory $settings
2020-10-04 16:35:33 +02:00
* @return Promise<self>
*/
2020-10-23 18:19:20 +02:00
public static function getInstance(string $table, $previous, $settings): Promise
2020-04-25 21:57:55 +02:00
{
2020-10-23 18:19:20 +02:00
return call(static function () use ($previous) {
if ($previous instanceof MemoryArray) {
return $previous;
}
2020-10-23 18:19:20 +02:00
if ($previous instanceof DbArray) {
Logger::log("Loading database to memory. Please wait.", Logger::WARNING);
2020-10-23 18:19:20 +02:00
if ($previous instanceof DriverArray) {
yield from $previous->initStartup();
}
2020-10-23 18:19:20 +02:00
$previous = yield $previous->getArrayCopy();
2020-05-17 21:04:32 +02:00
}
2020-10-23 18:19:20 +02:00
return new static($previous);
2020-05-17 21:04:32 +02:00
});
2020-04-25 21:57:55 +02:00
}
2020-04-28 02:41:06 +02:00
public function offsetExists($offset)
2020-04-28 02:41:06 +02:00
{
throw new \RuntimeException('Native isset not support promises. Use isset method');
}
public function isset($key): Promise
{
return new Success(parent::offsetExists($key));
2020-04-28 02:41:06 +02:00
}
2020-05-03 03:33:54 +02:00
public function offsetGet($offset): Promise
2020-04-28 02:41:06 +02:00
{
return new Success(parent::offsetExists($offset) ? parent::offsetGet($offset) : null);
2020-04-28 02:41:06 +02:00
}
2020-05-03 03:33:54 +02:00
public function offsetUnset($offset): Promise
2020-04-28 02:41:06 +02:00
{
return new Success(parent::offsetUnset($offset));
2020-05-03 03:33:54 +02:00
}
public function count(): Promise
{
return new Success(parent::count());
2020-05-03 03:33:54 +02:00
}
public function getArrayCopy(): Promise
2020-05-03 03:33:54 +02:00
{
return new Success(parent::getArrayCopy());
2020-04-28 02:41:06 +02:00
}
public function getIterator(): Producer
{
return new Producer(function (callable $emit) {
2020-05-03 03:33:54 +02:00
foreach ($this as $key => $value) {
yield $emit([$key, $value]);
2020-04-28 02:41:06 +02:00
}
});
}
2020-06-16 17:52:55 +02:00
}