1
0
mirror of https://github.com/danog/MadelineProto.git synced 2024-11-30 05:58:58 +01:00

Start refactoring external API

This commit is contained in:
Daniil Gentili 2023-01-08 20:33:54 +01:00
parent 60bf3290f8
commit 73e1d315b3
26 changed files with 1583 additions and 1019 deletions

View File

@ -24,86 +24,103 @@ class APIFactory extends AbstractAPIFactory
{
/**
* @internal this is a internal property generated by build_docs.php, don't change manually
*
* @var stats
*/
public $stats;
/**
* @internal this is a internal property generated by build_docs.php, don't change manually
*
* @var folders
*/
public $folders;
/**
* @internal this is a internal property generated by build_docs.php, don't change manually
*
* @var langpack
*/
public $langpack;
/**
* @internal this is a internal property generated by build_docs.php, don't change manually
*
* @var phone
*/
public $phone;
/**
* @internal this is a internal property generated by build_docs.php, don't change manually
*
* @var stickers
*/
public $stickers;
/**
* @internal this is a internal property generated by build_docs.php, don't change manually
*
* @var payments
*/
public $payments;
/**
* @internal this is a internal property generated by build_docs.php, don't change manually
*
* @var bots
*/
public $bots;
/**
* @internal this is a internal property generated by build_docs.php, don't change manually
*
* @var channels
*/
public $channels;
/**
* @internal this is a internal property generated by build_docs.php, don't change manually
*
* @var help
*/
public $help;
/**
* @internal this is a internal property generated by build_docs.php, don't change manually
*
* @var upload
*/
public $upload;
/**
* @internal this is a internal property generated by build_docs.php, don't change manually
*
* @var photos
*/
public $photos;
/**
* @internal this is a internal property generated by build_docs.php, don't change manually
*
* @var updates
*/
public $updates;
/**
* @internal this is a internal property generated by build_docs.php, don't change manually
*
* @var messages
*/
public $messages;
/**
* @internal this is a internal property generated by build_docs.php, don't change manually
*
* @var contacts
*/
public $contacts;
/**
* @internal this is a internal property generated by build_docs.php, don't change manually
*
* @var users
*/
public $users;
/**
* @internal this is a internal property generated by build_docs.php, don't change manually
*
* @var account
*/
public $account;
/**
* @internal this is a internal property generated by build_docs.php, don't change manually
*
* @var auth
*/
public $auth;

View File

@ -159,8 +159,6 @@ final class APIWrapper
/**
* Serialize session.
*
* @return Promise<bool>
*/
public function serialize(): bool
{

View File

@ -28,6 +28,7 @@ use phpDocumentor\Reflection\DocBlockFactory;
use ReflectionClass;
use ReflectionMethod;
use ReflectionNamedType;
use ReflectionType;
use ReflectionUnionType;
class AnnotationsBuilder
@ -62,13 +63,7 @@ class AnnotationsBuilder
$this->logger = $logger;
$this->namespace = $namespace;
/** @psalm-suppress InvalidArgument */
$this->TL = new TL(new class($logger) {
public Logger $logger;
public function __construct(Logger $logger)
{
$this->logger = $logger;
}
});
$this->TL = new TL();
$tlSchema = new TLSchema;
$tlSchema->mergeArray($settings);
$this->TL->init($tlSchema);
@ -178,15 +173,15 @@ class AnnotationsBuilder
$methods = \array_merge($methods, $class->getMethods((ReflectionMethod::IS_STATIC & ReflectionMethod::IS_PUBLIC) | ReflectionMethod::IS_PUBLIC));
foreach ($methods as $key => $method) {
$name = $method->getName();
if ($method == 'methodCallAsyncRead') {
if ($name == 'methodCallAsyncRead') {
unset($methods[\array_search('methodCall', $methods)]);
} elseif (\strpos($name, '__') === 0) {
unset($methods[$key]);
} elseif (\stripos($name, 'async') !== false) {
if (\strpos($name, '_async') !== false) {
unset($methods[\array_search(\str_ireplace('_async', '', $method), $methods)]);
unset($methods[\array_search(\str_ireplace('_async', '', $name), $methods)]);
} else {
unset($methods[\array_search(\str_ireplace('async', '', $method), $methods)]);
unset($methods[\array_search(\str_ireplace('async', '', $name), $methods)]);
}
}
}
@ -236,25 +231,7 @@ class AnnotationsBuilder
$hasVariadic = false;
foreach ($method->getParameters() as $param) {
if ($type = $param->getType()) {
if ($type instanceof ReflectionNamedType) {
if ($type->allowsNull()) {
$doc .= '?';
}
if (!$type->isBuiltin()) {
$doc .= '\\';
}
$doc .= $type->getName();
$doc .= ' ';
} elseif ($type instanceof ReflectionUnionType) {
foreach ($type->getTypes() as $t) {
if (!$t->isBuiltin()) {
$doc .= '\\';
}
$doc .= $t->getName();
$doc .= '|';
}
$doc[\strlen($doc)-1] = ' ';
}
$doc .= $this->typeToStr($type).' ';
} else {
Logger::log($name.'.'.$param->getName().' has no type!', Logger::WARNING);
}
@ -296,13 +273,7 @@ class AnnotationsBuilder
$async = true;
if ($hasReturnValue && $static) {
$doc .= ': ';
if ($type->allowsNull()) {
$doc .= '?';
}
if (!$type->isBuiltin()) {
$doc .= '\\';
}
$doc .= $type->getName() === 'self' ? $this->reflectionClasses['API'] : $type->getName();
$doc .= $this->typeToStr($type);
$async = false;
}
if ($method->getDeclaringClass()->getName() == Tools::class) {
@ -348,25 +319,7 @@ class AnnotationsBuilder
$ret = $matches[1];
$new = $ret;
if ($type && !\str_contains($ret, '<')) {
$new = '';
if ($type instanceof ReflectionNamedType) {
if ($type->allowsNull()) {
$new .= '?';
}
if (!$type->isBuiltin()) {
$new .= '\\';
}
$new .= $type->getName() === 'self' ? $this->reflectionClasses['API'] : $type;
} elseif ($type instanceof ReflectionUnionType) {
foreach ($type->getTypes() as $t) {
if (!$t->isBuiltin()) {
$new .= '\\';
}
$new .= $t->getName() === 'self' ? $this->reflectionClasses['API'] : $t;
$new .= '|';
}
$new = \substr($new, 0, -1);
}
$new = $this->typeToStr($type);
}
$phpdoc = \str_replace('@return '.$ret, '@return mixed', $phpdoc);
if (!\str_contains($phpdoc, '@return')) {
@ -433,4 +386,21 @@ class AnnotationsBuilder
}
\fclose($handle);
}
private function typeToStr(ReflectionType $type): string
{
$new = '';
if ($type instanceof ReflectionNamedType) {
if ($type->allowsNull() && $type->getName() !== 'mixed') {
$new .= '?';
}
if (!$type->isBuiltin()) {
$new .= '\\';
}
$new .= $type->getName() === 'self' ? $this->reflectionClasses['API'] : $type->getName();
} elseif ($type instanceof ReflectionUnionType) {
return \implode('|', \array_map($this->typeToStr(...), $type->getTypes()));
}
return $new;
}
}

View File

@ -5,7 +5,6 @@ declare(strict_types=1);
namespace danog\MadelineProto\Db;
use danog\MadelineProto\Logger;
use danog\MadelineProto\Settings\Database\DatabaseAbstract;
use danog\MadelineProto\Settings\Database\Memory;
use danog\MadelineProto\SettingsAbstract;
use ReflectionClass;
@ -22,10 +21,6 @@ abstract class DriverArray implements DbArray
use ArrayCacheTrait;
/**
* Initialize connection.
*/
abstract public function initConnection(DatabaseAbstract $settings): void;
/**
* Initialize on startup.
*/
@ -72,7 +67,7 @@ abstract class DriverArray implements DbArray
return $this->offsetGet($key) !== null;
}
public static function getInstance(string $table, DbArray|array|null $previous, $settings): static
public static function getInstance(string $table, DbType|array|null $previous, $settings): static
{
$instance = new static();
$instance->setTable($table);

View File

@ -5,7 +5,6 @@ declare(strict_types=1);
namespace danog\MadelineProto\Db;
use Amp\Mysql\ConnectionConfig;
use Amp\Sql\Result;
use danog\MadelineProto\Db\Driver\Mysql;
use danog\MadelineProto\Exception;
use danog\MadelineProto\Logger;
@ -91,10 +90,10 @@ class MysqlArray extends SqlArray
*
* @throws Throwable
*/
protected function prepareTable(): Result
protected function prepareTable(): void
{
Logger::log("Creating/checking table {$this->table}", Logger::WARNING);
return $this->db->query("
$this->db->query("
CREATE TABLE IF NOT EXISTS `{$this->table}`
(
`key` VARCHAR(255) NOT NULL,

View File

@ -25,9 +25,9 @@ class RedisArray extends DriverArray
/**
* Initialize on startup.
*/
public function initStartup()
public function initStartup(): void
{
return $this->initConnection($this->dbSettings);
$this->initConnection($this->dbSettings);
}
protected function prepareTable(): void
{
@ -151,7 +151,7 @@ class RedisArray extends DriverArray
* Count elements.
*
* @link https://php.net/manual/en/arrayiterator.count.php
* @return Promise<int> The number of elements or public properties in the associated
* @return int The number of elements or public properties in the associated
* array or object, respectively.
* @throws Throwable
*/

View File

@ -145,7 +145,6 @@ abstract class SqlArray extends DriverArray
* Unset value for an offset.
*
* @link https://php.net/manual/en/arrayiterator.offsetunset.php
* @return Promise<array>
* @throws Throwable
*/
public function unset(string|int $key): void
@ -163,7 +162,7 @@ abstract class SqlArray extends DriverArray
* Count elements.
*
* @link https://php.net/manual/en/arrayiterator.count.php
* @return Promise<int> The number of elements or public properties in the associated
* @return int The number of elements or public properties in the associated
* array or object, respectively.
* @throws Throwable
*/

View File

@ -53,12 +53,7 @@ class DocsBuilder
$this->logger = $logger;
\set_error_handler(['\\danog\\MadelineProto\\Exception', 'ExceptionErrorHandler']);
/** @psalm-suppress InvalidArgument */
$this->TL = new TL(new class($logger) {
public function __construct($logger)
{
$this->logger = $logger;
}
});
$this->TL = new TL(null);
$new = new TLSchema;
$new->mergeArray($settings);
$this->TL->init($new);

View File

@ -49,20 +49,13 @@ class FileCallback implements FileCallbackInterface
/**
* Get file.
*/
public function getFile()
public function getFile(): mixed
{
return $this->file;
}
/**
* Invoke callback.
*
* @param int $percent Percent
* @param int $speed Speed in mbps
* @param int $time Time
*/
public function __invoke(int $percent, int $speed, int $time)
public function __invoke(float $percent, float $speed, float $time): void
{
$callback = $this->callback;
return $callback($percent, $speed, $time);
$callback($percent, $speed, $time);
}
}

View File

@ -28,7 +28,7 @@ interface FileCallbackInterface
/**
* Get file.
*/
public function getFile(): void;
public function getFile(): mixed;
/**
* Invoke callback.
*

File diff suppressed because it is too large Load Diff

View File

@ -65,11 +65,11 @@ abstract class ClientAbstract
/**
* Logger.
*
* @param string $param Parameter
* @param mixed $param Parameter
* @param int $level Logging level
* @param string $file File where the message originated
*/
public function logger(string $param, int $level = Logger::NOTICE, string $file = ''): void
public function logger(mixed $param, int $level = Logger::NOTICE, string $file = ''): void
{
if ($file === null) {
$file = \basename(\debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0]['file'], '.php');

View File

@ -54,9 +54,8 @@ final class ProcessRunner extends RunnerAbstract
* Runner.
*
* @param string $session Session path
* @return Promise<true>
*/
public static function start(string $session, int $startupId): boool
public static function start(string $session, int $startupId): bool
{
if (PHP_SAPI === 'cli') {
$binary = PHP_BINARY;

View File

@ -11,7 +11,7 @@ class FileCallback extends Obj implements FileCallbackInterface
/**
* Get file.
*/
public function getFile()
public function getFile(): mixed
{
return $this->__call('getFile');
}
@ -21,10 +21,9 @@ class FileCallback extends Obj implements FileCallbackInterface
* @param float $percent Percent
* @param float $speed Speed in mbps
* @param float $time Time
* @psalm-suppress MethodSignatureMismatch
*/
public function __invoke(float $percent, float $speed, float $time)
public function __invoke(float $percent, float $speed, float $time): void
{
return $this->__call('__invoke', [$percent, $speed, $time]);
$this->__call('__invoke', [$percent, $speed, $time]);
}
}

View File

@ -1,10 +0,0 @@
<?php
declare(strict_types=1);
namespace danog\MadelineProto\Ipc\Wrapper;
class SeekableInputStream extends InputStream
{
use SeekableTrait;
}

View File

@ -1,10 +0,0 @@
<?php
declare(strict_types=1);
namespace danog\MadelineProto\Ipc\Wrapper;
class SeekableOutputStream extends OutputStream
{
use SeekableTrait;
}

View File

@ -206,6 +206,7 @@ class ReadLoop extends SignalLoop
}
$API->logger->logger('Received payload from DC '.$datacenter, Logger::ULTRA_VERBOSE);
// TODO: A correct solution for side effects should be devised here...
$deserialized = $API->getTL()->deserialize($message_data, ['type' => '', 'connection' => $connection]);
if (isset($API->referenceDatabase)) {
$API->referenceDatabase->reset();

View File

@ -812,11 +812,11 @@ class MTProto implements TLCallback, LoggerGetter
/**
* Logger.
*
* @param string $param Parameter
* @param mixed $param Parameter
* @param int $level Logging level
* @param string $file File where the message originated
*/
public function logger(string $param, int $level = Logger::NOTICE, string $file = ''): void
public function logger(mixed $param, int $level = Logger::NOTICE, string $file = ''): void
{
if ($file === null) {
$file = \basename(\debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0]['file'], '.php');

View File

@ -49,10 +49,6 @@ class MyTelegramOrgWrapper
*
*/
private Settings $settings;
/**
* Async setting.
*/
private bool $async = true;
/**
* Datacenter instance.
*/
@ -305,15 +301,6 @@ class MyTelegramOrgWrapper
}
return $final_headers;
}
/**
* Enable or disable async.
*
* @param boolean $async Async
*/
public function async(bool $async): void
{
$this->async = $async;
}
/**
* Run specified callable synchronously.
*
@ -323,19 +310,4 @@ class MyTelegramOrgWrapper
{
return Tools::wait($callable());
}
/**
* Call function.
*
* @param string $name Function name
* @param array $arguments Arguments
*/
public function __call(string $name, array $arguments)
{
$name .= '_async';
$async = \is_array(\end($arguments)) && isset(\end($arguments)['async']) ? \end($arguments)['async'] : $this->async;
if (!\method_exists($this, $name)) {
throw new Exception("{$name} does not exist!");
}
return $async ? $this->{$name}(...$arguments) : Tools::wait($this->{$name}(...$arguments));
}
}

View File

@ -102,11 +102,6 @@ abstract class DatabaseAbstract extends SettingsDatabaseAbstract
*/
abstract public function getUri(): string;
/**
* Set database name/ID.
*
*/
abstract public function setDatabase(int|string $database): self;
/**
* Set database URI.
*/

View File

@ -120,7 +120,7 @@ class CtrStream implements BufferedProxyStreamInterface, BufferInterface
throw new Exception('Tried to send too much out of frame data, cannot append');
}
}
return $this->write_buffer->bufferWrite(@$this->encrypt->encrypt($data));
$this->write_buffer->bufferWrite(@$this->encrypt->encrypt($data));
}
/**
* Set obfuscation keys/IVs.

View File

@ -144,7 +144,7 @@ class FileBufferedStream implements BufferedStreamInterface, BufferInterface, Pr
throw new Exception('Tried to send too much out of frame data, cannot append');
}
}
return $this->write($data);
$this->write($data);
}
/**
* Set file handle.

View File

@ -32,5 +32,5 @@ interface ProxyStreamInterface
*
* @param mixed $extra Proxy data
*/
public function setExtra(mixed $extra): void;
public function setExtra($extra): void;
}

View File

@ -87,7 +87,7 @@ final class TL
/**
* API instance.
*/
private MTProto $API;
private ?MTProto $API = null;
public function __sleep()
{
return [
@ -107,7 +107,9 @@ final class TL
*/
public function __construct(?MTProto $API = null)
{
$this->API = $API;
if ($API) {
$this->API = $API;
}
}
/**
* Get secret chat layer version.
@ -145,7 +147,7 @@ final class TL
*/
public function init(TLSchema $files, array $objects = []): void
{
$this->API->logger->logger(Lang::$current_lang['TL_loading'], Logger::VERBOSE);
$this->API?->logger?->logger(Lang::$current_lang['TL_loading'], Logger::VERBOSE);
$this->updateCallbacks($objects);
$this->constructors = new TLConstructors();
$this->methods = new TLMethods();
@ -158,7 +160,7 @@ final class TL
'secret' => $files->getSecretSchema(),
...$files->getOther(),
]) as $scheme_type => $file) {
$this->API->logger->logger(\sprintf(Lang::$current_lang['file_parsing'], \basename($file)), Logger::VERBOSE);
$this->API?->logger?->logger(\sprintf(Lang::$current_lang['file_parsing'], \basename($file)), Logger::VERBOSE);
$filec = \file_get_contents(Tools::absolute($file));
$TL_dict = \json_decode($filec, true);
if ($TL_dict === null) {
@ -248,7 +250,7 @@ final class TL
if (\preg_match('/^[^\\s]+#([a-f0-9]*)/i', $line, $matches)) {
$nid = \str_pad($matches[1], 8, '0', STR_PAD_LEFT);
if ($id !== $nid) {
$this->API->logger->logger(\sprintf(Lang::$current_lang['crc32_mismatch'], $id, $nid, $line), Logger::ERROR);
$this->API?->logger?->logger(\sprintf(Lang::$current_lang['crc32_mismatch'], $id, $nid, $line), Logger::ERROR);
}
$id = $nid;
}
@ -293,14 +295,14 @@ final class TL
if (empty($TL_dict) || empty($TL_dict['constructors']) || !isset($TL_dict['methods'])) {
throw new Exception(Lang::$current_lang['src_file_invalid'].$file);
}
$this->API->logger->logger(Lang::$current_lang['translating_obj'], Logger::ULTRA_VERBOSE);
$this->API?->logger?->logger(Lang::$current_lang['translating_obj'], Logger::ULTRA_VERBOSE);
foreach ($TL_dict['constructors'] as $elem) {
if ($scheme_type === 'secret') {
$this->secretLayer = \max($this->secretLayer, $elem['layer']);
}
$this->{$scheme_type === 'td' ? 'tdConstructors' : 'constructors'}->add($elem, $scheme_type);
}
$this->API->logger->logger(Lang::$current_lang['translating_methods'], Logger::ULTRA_VERBOSE);
$this->API?->logger?->logger(Lang::$current_lang['translating_methods'], Logger::ULTRA_VERBOSE);
foreach ($TL_dict['methods'] as $elem) {
$this->{$scheme_type === 'td' ? 'tdMethods' : 'methods'}->add($elem);
if ($scheme_type === 'secret') {

View File

@ -990,12 +990,12 @@ class InternalDoc extends APIFactory
/**
* Logger.
*
* @param string $param Parameter
* @param mixed $param Parameter
* @param int $level Logging level
* @param string $file File where the message originated
* @return void|Promise<void>
*/
public function logger(string $param, int $level = Logger::NOTICE, string $file = ''): void
public function logger(mixed $param, int $level = Logger::NOTICE, string $file = ''): void
{
$this->__call(__FUNCTION__, [$param, $level, $file]);
}

View File

@ -93,11 +93,11 @@ class Lite
/**
* Logger.
*
* @param string $param Parameter
* @param mixed $param Parameter
* @param int $level Logging level
* @param string $file File where the message originated
*/
public function logger(string $param, int $level = Logger::NOTICE, string $file = ''): void
public function logger(mixed $param, int $level = Logger::NOTICE, string $file = ''): void
{
if ($file === null) {
$file = \basename(\debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0]['file'], '.php');