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

70 lines
1.8 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 danog\MadelineProto\Logger;
2020-04-28 02:41:06 +02:00
use function Amp\call;
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
2020-05-17 21:04:32 +02:00
public static function getInstance(string $name, $value = null, string $tablePrefix = '', array $settings = []): Promise
2020-04-25 21:57:55 +02:00
{
2020-06-16 17:52:55 +02:00
return call(static function () use ($value) {
if ($value instanceof MemoryArray) {
return $value;
}
2020-05-17 21:04:32 +02:00
if ($value instanceof DbArray) {
Logger::log("Loading database to memory. Please wait.", Logger::WARNING);
$value = yield $value->getArrayCopy();
2020-05-17 21:04:32 +02:00
}
return new static($value);
});
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
{
2020-06-16 17:52:55 +02:00
return call(fn () => 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
{
2020-06-16 17:52:55 +02:00
return call(fn () => 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
{
2020-06-16 17:52:55 +02:00
return call(fn () => parent::offsetUnset($offset));
2020-05-03 03:33:54 +02:00
}
public function count(): Promise
{
2020-06-16 17:52:55 +02:00
return call(fn () => parent::count());
2020-05-03 03:33:54 +02:00
}
public function getArrayCopy(): Promise
2020-05-03 03:33:54 +02:00
{
2020-06-16 17:52:55 +02:00
return call(fn () => 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
}