MadelineProto/src/danog/MadelineProto/Db/DriverArray.php

81 lines
2.3 KiB
PHP
Raw Normal View History

<?php
namespace danog\MadelineProto\Db;
use danog\MadelineProto\Logger;
use danog\MadelineProto\SettingsAbstract;
use ReflectionClass;
2020-10-03 12:36:08 +02:00
/**
2020-10-03 15:04:35 +02:00
* Array caching trait.
2020-10-03 12:36:08 +02:00
*/
abstract class DriverArray implements DbArray
{
use ArrayCacheTrait;
public function __destruct()
{
$this->stopCacheCleanupLoop();
}
/**
* Get string representation of driver/table.
*
* @return string
*/
abstract public function __toString(): string;
2020-09-12 19:06:42 +02:00
public function __wakeup()
{
if (isset($this->settings) && \is_array($this->settings)) {
$clazz = (new ReflectionClass($this))->getProperty('dbSettings')->getType()->getName();
2020-10-06 20:37:11 +02:00
/**
* @var SettingsAbstract
2020-10-04 16:35:33 +02:00
* @psalm-suppress UndefinedThisPropertyAssignment
*/
$this->dbSettings = new $clazz;
$this->dbSettings->mergeArray($this->settings);
unset($this->settings);
}
}
2020-09-12 19:06:42 +02:00
public function offsetExists($index): bool
{
throw new \RuntimeException('Native isset not support promises. Use isset method');
}
2020-10-02 16:13:19 +02:00
abstract public function initConnection(\danog\MadelineProto\Settings\Database\DatabaseAbstract $settings): \Generator;
2020-09-28 23:20:12 +02:00
abstract public function initStartup(): \Generator;
/**
* @param self $new
* @param DbArray|array|null $old
*
* @return \Generator
* @throws \Throwable
*/
protected static function migrateDataToDb(self $new, $old): \Generator
{
if (!empty($old) && !$old instanceof static) {
Logger::log('Converting database.', Logger::ERROR);
if ($old instanceof DbArray) {
$old = yield $old->getArrayCopy();
} else {
$old = (array) $old;
}
$counter = 0;
$total = \count($old);
foreach ($old as $key => $item) {
$counter++;
if ($counter % 500 === 0) {
yield $new->offsetSet($key, $item);
Logger::log("Loading data to table {$new}: $counter/$total", Logger::WARNING);
} else {
$new->offsetSet($key, $item);
}
}
Logger::log('Converting database done.', Logger::ERROR);
}
}
}