9 Commits
3.4.x ... 4.3.0

18 changed files with 939 additions and 492 deletions

4
.gitignore vendored
View File

@@ -1 +1,3 @@
/vendor
!.gitignore
composer.phar
vendor

View File

@@ -1,5 +1,5 @@
# Колпачный фреймворк для ВКонтакте
Развивается как многопоточный фреймворк с поддержкой всех возможностей API ВКонтакте, а так же не добавленных, но необходимых функций, работу с большим количеством роботов под разными сессиями, поддерживающий PSR-спецификацию и полностью покрытый тестами
# PHP-фреймворк ВКонтакте
Многопоточный фреймворк с поддержкой всех возможностей API ВКонтакте
### Установка:
```sh

View File

@@ -1,35 +1,39 @@
{
"name": "mirzaev/vk",
"type": "framework",
"description": "Фреймворк VK API",
"description": "Framework for vk.com API",
"readme": "README.md",
"keywords": [
"vk",
"api"
],
"homepage": "https://git.hood.su/mirzaev/vk",
"homepage": "https://git.mirzaev.sexy/mirzaev/vk",
"license": "WTFPL",
"authors": [
{
"name": "Arsen Mirzaev Tatyano-Muradovich",
"email": "red@hood.su",
"homepage": "https://hood.su/mirzaev",
"email": "arsen@mirzaev.sexy",
"homepage": "https://mirzaev.sexy/mirzaev",
"role": "Programmer"
}
],
"support": {
"docs": "https://git.hood.su/mirzaev/vk/manual",
"issues": "https://git.hood.su/mirzaev/vk/issues"
"docs": "https://git.mirzaev.sexy/mirzaev/vk/wiki",
"issues": "https://git.mirzaev.sexy/mirzaev/vk/issues"
},
"require": {
"php": "~8.0",
"psr/log": "~1.0",
"mirzaev/accounts": "~0.1.x-dev",
"monolog/monolog": "~1.6",
"jasny/error-handler": "~0.2",
"guzzlehttp/guzzle": "~7.2"
"php": "^8.1",
"psr/log": "^1.0",
"mirzaev/accounts": "^1.2.0",
"monolog/monolog": "^1.6",
"jasny/error-handler": "^0.2",
"guzzlehttp/guzzle": "^7.5"
},
"require-dev": {
"phpunit/phpunit": "~9.5"
"phpunit/phpunit": "^9.5"
},
"suggest": {
"ext-sodium": "Can be selected in some conditions to increase security"
},
"autoload": {
"psr-4": {

618
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -2,7 +2,7 @@
// declare(strict_types=1);
// namespace Hood\VK\API;
// namespace mirzaev\vk\API;
// class CallBack extends CallBackAbstract
// {

View File

@@ -7,7 +7,8 @@ namespace mirzaev\vk\api;
use Exception;
use mirzaev\vk\core,
mirzaev\vk\robots\robot;
mirzaev\vk\robots\robot,
mirzaev\vk\robots\group;
/**
* LongPoll
@@ -25,7 +26,7 @@ use mirzaev\vk\core,
* @see https://vk.com/dev/groups.setLongPollSettings
*
* @package mirzaev\vk\api
* @author Arsen Mirzaev Tatyano-Muradovich <red@hood.su>
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*
* @todo Добавить обработку ошибок ($request['errors];)
*/
@@ -36,14 +37,14 @@ final class longpoll
*
* @see $this->get()
*/
private string $key;
private readonly string $key;
/**
* Сервер (URL)
*
* @see $this->get()
*/
private string $server;
private readonly string $server;
/**
* Идентификатор последнего события
@@ -59,7 +60,7 @@ final class longpoll
*
* $robot Робот
*/
public function __construct(private robot $robot)
public function __construct(private robot&group $robot)
{
// Инициализация
if (empty($robot->id)) throw new Exception('Необходимо указать идентификатор ВКонтакте');

View File

@@ -0,0 +1,115 @@
<?php
declare(strict_types=1);
namespace mirzaev\vk\api\methods;
// Файлы проекта
use mirzaev\vk\robots\user;
// Встроенные библиотеки
use Exception;
/**
* Аккаунт
*
* @method public getInfo(?array $fields = null) Запросить информацию об аккаунте
* @method public getProfileInfo(?array $fields = null) Запросить информацию о профиле
*
* @see https://dev.vk.com/method/account
*
* @package mirzaev\vk\api
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*/
final class account extends method
{
/**
* Конструктор
*
* @param user $user Робот
*/
public function __construct(
protected user $robot
) {
}
/**
* Запросить информацию об аккаунте
*
* @see https://dev.vk.com/method/account.getInfo
*
* @param array $fields Выбор полей с запрашиваемой информацией (оставить пустым, если нужны все)
*
* @return ?array Информация об аккаунте, если получена
*
* @todo
* 1. Доделать
* 2. Написать обработчик ошибок возвращаемых ВКонтакте
*/
public function getInfo(array $fields = []): array
{
// Реиницилазиция
$this->robot->api->reinit();
foreach ($fields as $key => $field) {
// Перебор запрашиваемых полей с информацией
// Запись запрашиваемого поля
$this->robot->api['fields'] .= $field;
// Запись разделителя
if ($key === array_key_last($fields)) break;
else $this->robot->api['fields'] .= ', ';
}
// Запрос
$request = json_decode($this->robot->browser->request('POST', 'account.getInfo', ['form_params' => $this->robot->api->settings])->getBody()->getContents());
// Если в ответе ошибка
if (isset($request->error)) {
throw new Exception('ВКонтакте: ' . $request->error->error_msg, $request->error->error_code);
}
return $request->response;
}
/**
* Запросить информацию о профиле
*
* @see https://dev.vk.com/method/account.getProfileInfo
*
* @param array $fields Выбор полей с запрашиваемой информацией (оставить пустым, если нужны все)
*
* @return ?array Информация об аккаунте, если получена
*
* @todo
* 1. Доделать
* 2. Написать обработчик ошибок возвращаемых ВКонтакте
*/
public function getProfileInfo(array $fields = []): array
{
// Реиницилазиция
$this->robot->api->reinit();
foreach ($fields as $key => $field) {
// Перебор запрашиваемых полей с информацией
// Запись запрашиваемого поля
$this->robot->api['fields'] .= $field;
// Запись разделителя
if ($key === array_key_last($fields)) break;
else $this->robot->api['fields'] .= ', ';
}
// Запрос
$request = json_decode($this->robot->browser->request('POST', 'account.getProfileInfo', ['form_params' => $this->robot->api->settings])->getBody()->getContents());
// Если в ответе ошибка
if (isset($request->error)) {
throw new Exception('ВКонтакте: ' . $request->error->error_msg, $request->error->error_code);
}
return $request->response;
}
}

View File

@@ -4,12 +4,43 @@ declare(strict_types=1);
namespace mirzaev\vk\api\methods;
use Exception;
// Файлы проекта
use mirzaev\vk\robots\robot,
mirzaev\vk\robots\group;
use mirzaev\accounts\vk;
use mirzaev\vk\robots\robot;
use mirzaev\vk\api\data;
use mirzaev\vk\robots\group;
// Встроенные библиотеки
use stdClass,
Exception;
/**
* Режимы отправки сообщений
*/
enum send
{
/** Обычная отправка */
case simple;
/** Проверка отправки */
case check;
}
/**
* Режимы генерации идентификатора сессии доставки сообщения
*/
enum generate
{
/** Генерация: time() */
case date;
/** Генерация: rand() */
case random;
/** Генерация: random_bytes(10) */
case crypto;
/** Генерация: sodium_crypto_generichash() */
case hash;
}
/**
* Сообщение
@@ -20,43 +51,88 @@ use mirzaev\vk\robots\group;
* @see https://vk.com/dev/messages.getById
*
* @package mirzaev\vk\api
* @author Arsen Mirzaev Tatyano-Muradovich <red@hood.su>
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*
* @todo Доработать строгий режим отправки: проверку сообщения в беседе (не имеет ID сообщений)
*/
final class messages extends method
{
/**
* @var int $mode Режим отправки
* @var send $send_mode Режим отправки сообщений
*/
protected int $mode = 1;
protected send $send_mode = send::simple;
/**
* @var array[int] Сообщения для пересылки
* @var generate $generate_mode Режим генерации идентификатора сессии доставки сообщения
*/
protected array $forward;
protected generate $generate_mode = generate::date;
/**
* @var int Сообщение для ответа
* @var ?int $lat Географическая ширина
*/
protected int $reply;
protected ?int $lat = null;
/**
* @var ?int $long Географическая долгота
*/
protected ?int $long = null;
/**
* @var ?int $reply_to Идентификатор сообщения, на которое требуется ответить
*/
protected ?int $reply_to = null;
/**
* @var ?array $forward_messages Идентификаторы пересылаемых сообщений
*/
protected ?array $forward_messages = null;
/**
* @var ?string $sticker_id Идентификатор стикера
*/
protected ?string $sticker_id = null;
/**
* @var ?string $payload Полезная нагрузка
*/
protected ?string $payload = null;
/**
* @var bool $dont_parse_links Не создавать представление ссылки в сообщении?
*/
protected bool $dont_parse_links = false;
/**
* @var bool $disable_mentions Отключить уведомление об упоминании в сообщении?
*/
protected bool $disable_mentions = false;
/**
* @var ?string $intent Интент
*/
protected ?string $intent = null;
/**
* @var ?string $subscribe_id Число, которое будет использоваться для работы с интентами
*/
protected ?int $subscribe_id = null;
/**
* Конструктор
*
* @param robot $robot Робот
* @param int|string|array|null $destination Получатель
* @param int|string|array|null $receiver Получатель
* @param string|null $text Текст
*/
public function __construct(
protected robot $robot,
int|string|array|null $destination = null,
int|string|array|null $receiver = null,
protected string|null $text = null
) {
if (isset($this->text, $destination)) {
if (isset($this->text, $receiver)) {
// Быстрая отправка
$this->send($destination);
$this->send($receiver);
}
}
@@ -108,65 +184,133 @@ final class messages extends method
*
* @see https://vk.com/dev/messages.send
*
* @param int|string|array|null $destination Получатель
* @param int|string|null $receiver Получатель
* @param ?string $message Сообщение
* @param ?int $lat Географическая ширина
* @param ?int $long Географическая долгота
* @param ?array $attachments Вложения
* @param ?int $reply_to Идентификатор сообщения, на которое требуется ответить
* @param ?array $forward_messages Идентификаторы пересылаемых сообщений
* @param ?forward $forward Пересылаемые сообщения (в другой чат)
* @param ?string $sticker_id Идентификатор стикера
* @param ?keyboard $keyboard Инстанция клавиатуры
* @param ?template $template Инстанция шаблона сообщения
* @param ?string $payload Полезная нагрузка
* @param bool $dont_parse_links Не создавать представление ссылки в сообщении?
* @param bool $disable_mentions Отключить уведомление об упоминании в сообщении?
* @param ?string $intent Интент
* @param ?int $subscribe_id Число, которое будет использоваться для работы с интентами
* @param int|string|null $random_id Идентификатор сессии доставки сообщения (защита от повторных отправок)
*
* @return int|array Идентификатор успешно отправленного сообщения или ответ сервера (подразумевается ошибка)
*
* @todo Написать обработчик ошибок возвращаемых ВКонтакте
* @todo
* 1. Написать обработчик ошибок возвращаемых ВКонтакте
* 2. Добавить параметр forward (не путать с forward_messages)
* 3. Добавить клавиатуру
* 4. Добавить шаблоны сообщений
* 5. Добавить content_source
*/
public function send(int|string|array|null $destination): int|array
{
// Идентификатор
$random_id = time();
if ($this->mode = 1) {
// Перемножение (по умолчанию)
$random_id *= rand();
}
// Реиницилазиция
public function send(
int|string|null $receiver,
?string $message = null,
?int $lat = null,
?int $long = null,
?array $attachments = null,
?int $reply_to = null,
?array $forward_messages = null,
// ?forward $forward = null,
?string $sticker_id = null,
// ?keyboard $keyboard = null,
// ?template $template = null,
?string $payload = null,
bool $dont_parse_links = false,
bool $disable_mentions = false,
?string $intent = null,
?int $subscribe_id = null,
int|string|null $random_id = null,
): int|array {
// Реинициализация настроек
$this->robot->api->reinit();
// Цель отправки
$this->robot->api->destination($destination);
// Инициализация получателя
if (is_int($receiver)) ($id = $receiver - 2000000000) > 0 ? $this->robot->api['peer_id'] = $receiver : $this->robot->api['chat_id'] = $id;
else if (is_array($receiver)) $this->robot->api['peer_ids'] = implode(',', $receiver);
else if (is_string($receiver)) $this->robot->api['domain'] = $receiver;
// Инициализация идентификатора (защита от повторных отправок) в настройках API
$this->robot->api['random_id'] = $random_id;
// Инициализация идентификатора сессии доставки сообщения (защита от повторных отправок)
$this->robot->api['random_id'] = $random_id ?? match ($this->generate_mode) {
generate::date => time(),
generate::random => rand(),
generate::crypto => random_bytes(10),
generate::hash => sodium_crypto_generichash(random_bytes(10)),
default => time()
};
// Инициализация текста в настройках API
$this->robot->api['message'] = $this->text;
if (isset($message)) $this->robot->api['message'] = $message;
else if (isset($this->text)) $this->robot->api['message'] = $this->text;
// Пересылаемые сообщения
if (!empty($this->forwardMessages)) {
// Инициализация широты
if (isset($lat)) $this->robot->api['lat'] = $lat;
else if (isset($this->lat)) $this->robot->api['lat'] = $this->lat;
// Инициализация пересылаемых сообщений в настройках API
$this->robot->api['forward_messages'] = implode(',', $this->forwardMessages);
}
// Инициализация долготы
if (isset($long)) $this->robot->api['long'] = $long;
else if (isset($this->long)) $this->robot->api['long'] = $this->tlongext;
// Ответные сообщения
if (isset($this->ReplyMessage)) {
// Инициализация вложений
if (isset($attachments)) $this->robot->api['attachment'] = implode(',', $attachments);
else if (isset($this->robot->api->data) && $this->robot->api->__get('data') !== []) $this->robot->api['attachment'] = implode(',', $this->robot->api->__get('data'));
// Инициализация идентификатора сообщения на которое обрабатывается ответ в настройках API
$this->robot->api['reply_to'] = $this->ReplyMessage;
}
// Инициализация сообщения, на которое требуется ответить
if (isset($reply_to)) $this->robot->api['reply_to'] = $reply_to;
else if (isset($this->reply)) $this->robot->api['reply_to'] = $this->reply;
// Вложения
if (isset($this->data) && $this->__get('data') !== []) { // !empty($this->data->data) почемуто не работает
// Инициализация пересылаемых сообщений
if (isset($forward_messages)) $this->robot->api['forward_messages'] = implode(',', $forward_messages);
else if (isset($this->forward_messages)) $this->robot->api['forward_messages'] = implode(',', $this->forward_messages);
// Инициализация вложений в настройках API
$this->robot->api['attachment'] = implode(',', $this->__get('data'));
}
// Инициализация стикера
if (isset($sticker_id)) $this->robot->api['sticker_id'] = $sticker_id;
else if (isset($this->sticker_id)) $this->robot->api['sticker_id'] = $this->sticker_id;
// Инициализация полезной нагрузки
if (isset($payload)) $this->robot->api['payload'] = $payload;
else if (isset($this->payload)) $this->robot->api['payload'] = $this->payload;
// Инициализация пользовательского соглашения
// $this->robot->api['content_source'] = $this->robot->content_source;
// Инициализация "не создавать представление ссылки в сообщении?"
if ($dont_parse_links) $this->robot->api['dont_parse_links'] = 1;
else if ($this->dont_parse_links) $this->robot->api['dont_parse_links'] = 1;
// Инициализация "отключить уведомление об упоминании в сообщении?"
if ($disable_mentions) $this->robot->api['disable_mentions'] = 1;
else if ($this->disable_mentions) $this->robot->api['disable_mentions'] = 1;
// Инициализация интентов
if (isset($intent)) $this->robot->api['intent'] = $intent;
else if (isset($this->intent)) $this->robot->api['intent'] = $this->intent;
// Инициализация числа, которое будет использоваться для работы с интентами
if (isset($subscribe_id)) $this->robot->api['subscribe_id'] = $subscribe_id;
else if (isset($this->subscribe_id)) $this->robot->api['subscribe_id'] = $this->subscribe_id;
// Проверка сформированного сообщения
if (!$this->robot->api->offsetExists('message') && !$this->robot->api->offsetExists('attachment')) throw new Exception('Сообщение должно содержать текст, либо вложение');
// Запрос
$request = json_decode($this->robot->browser->request('POST', 'messages.send', ['form_params' => $this->robot->api->settings])->getBody()->getContents());
// Если в ответе ошибка
if (isset($request->error)) {
throw new Exception('Вконтакте: ' . $request->error->error_msg, $request->error->error_code);
throw new Exception('ВКонтакте: ' . $request->error->error_msg, $request->error->error_code);
}
if ($this->mode >= 2) {
// Если установлен режим 2 (усиленная проверка отправленного сообщения)
if ($this->send_mode === send::check) {
// Надёжная доставка сообщения
if (!empty($request["response"])) {
// Ответ получен
@@ -177,7 +321,6 @@ final class messages extends method
// Запрашиваемые сообщения
$this->robot->api['message_ids'] = $request["response"];
// Запрос
if ($this->robot->browser->request('POST', 'messages.getById', ['form_params' => $this->robot->api->settings])['response']['count'] === 0) {
// Сообщения не существует
//!!!!!!!!!!!!!!!!!!!!!!!!!!!
@@ -185,7 +328,7 @@ final class messages extends method
//!!!!!!!!!!!!!!!!!!!!!!!!!
// Повторная отправка
$this->send($destination);
$this->send($receiver);
}
} else {
}
@@ -194,6 +337,59 @@ final class messages extends method
return $request->response;
}
/**
* Удалить сообщение
*
* @see https://vk.com/dev/messages.delete
*
* @param int|string|array|null $messages Получатель (message_ids + cmids)
* @param int|string|null $peer_id Идентификатор беседы
* @param bool $spam Пометить как спам?
* @param bool $delete_for_all Удалить для всех?
*
* @return int|array Идентификатор успешно отправленного сообщения или ответ сервера (подразумевается ошибка)
*
* @todo Написать обработчик ошибок возвращаемых ВКонтакте
*/
public function delete(string|int|array|null $messages = null, int|string|null $peer_id = null, bool $spam = false, bool $delete_for_all = false): stdClass
{
// Реиницилазиция настроек
$this->robot->api->reinit();
if (isset($peer_id)) {
// Получен идентификатор беседы
// Инициализация идентификатора беседы
$this->robot->api['peer_id'] = $peer_id;
// Инициализация идентификаторов сообщений
$this->robot->api['cmids'] = $messages;
// Инициализация: "удалить для всех?"
$this->robot->api['delete_for_all'] = 1;
} else {
// Не получен идентификатор беседы
// Инициализация идентификаторов сообщений
$this->robot->api['message_ids'] = $messages;
// Инициализация: "удалить для всех?"
if ($delete_for_all) $this->robot->api['delete_for_all'] = 1;
}
// Инициализация: "сообщить о спаме?"
if ($spam) $this->robot->api['spam'] = $spam;
// Запрос
$request = json_decode($this->robot->browser->request('POST', 'messages.delete', ['form_params' => $this->robot->api->settings])->getBody()->getContents());
// Проверка на наличие ошибок в ответе от ВКонтакте
if (isset($request->error)) throw new Exception('ВКонтакте: ' . $request->error->error_msg, $request->error->error_code);
return $request->response;
}
/**
* Записать свойство
*

View File

@@ -4,58 +4,12 @@ declare(strict_types=1);
namespace mirzaev\vk\api\methods;
use mirzaev\vk\robots\robot;
/**
* Абстракция метода API
*
* @method protected static put(string $url, ...$params) Создать
* @method protected static post(string $url, ...$params) Изменить
* @method protected static get(string $url, ...$params) Получить
* @method protected static delete(string $url, ...$params) Удалить
* Абстракция метода API ВКонтакте
*
* @package mirzaev\vk\api\methods
* @author Arsen Mirzaev Tatyano-Muradovich <red@hood.su>
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*/
abstract class method
{
/**
* Создать
*
* @return array Ответ сервера
*/
public static function put(): array
{
return ['error' => 'Метод не поддерживается'];
}
/**
* Изменить
*
* @return array Ответ сервера
*/
public static function post(): array
{
return ['error' => 'Метод не поддерживается'];
}
/**
* Получить
*
* @return array Ответ сервера
*/
public static function get(): array
{
return ['error' => 'Метод не поддерживается'];
}
/**
* Удалить
*
* @return array Ответ сервера
*/
public static function delete(): array
{
return ['error' => 'Метод не поддерживается'];
}
}

View File

@@ -20,14 +20,14 @@ use mirzaev\accounts\vk as account;
* @see https://vk.com/dev/messages.getById
*
* @package mirzaev\vk\api\methods
* @author Arsen Mirzaev Tatyano-Muradovich <red@hood.su>
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*
* @todo Добавить обработку ошибок ($request['errors];)
*/
final class photos extends method
{
/**
* Создать сообщение
* Конструктор
*
* @param robot $robot Робот
*/

View File

@@ -0,0 +1,114 @@
<?php
declare(strict_types=1);
namespace mirzaev\vk\api\methods;
// Файлы проекта
use mirzaev\vk\robots\robot;
// Встроенные библиотеки
use Exception,
stdClass;
/**
* Пользователь
*
*
* @see https://dev.vk.com/method/users
*
* @package mirzaev\vk\api
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*/
final class users extends method
{
/**
* Конструктор
*
* @param robot $user Робот
*/
public function __construct(
protected robot $robot
) {
}
/**
* Запросить информацию о пользователе
*
* @see https://dev.vk.com/method/users.get
*
* @param array $receiver Выбор пользователей для запроса информации (user_ids)
* @param array $fields Выбор дополнительных запрашиваемых полей
* @param string $name_case Падеж
*
* @return stdClass|array|null Информация об аккаунте или массив с информацией об аккаунтах, если найдена
*
* @todo
* 1. Доделать
* 2. Написать обработчик ошибок возвращаемых ВКонтакте
*/
public function get(int|string|array $receiver = [], array $fields = [], ?string $name_case = null): stdClass|array|null
{
// Реиницилазиция
$this->robot->api->reinit();
if (is_int($receiver)) {
// Идентификатор
// Инициализация пользователя
$this->robot->api['user_ids'] = $receiver;
} else if (is_array($receiver)) {
// Идентификаторы
// Инициализация пользователей
$this->robot->api['user_ids'] = '';
foreach ($receiver as $key => $user_id) {
// Перебор пользователей для получения информации
// Запись пользователя
$this->robot->api['user_ids'] .= $user_id;
// Запись разделителя
if ($key === array_key_last($receiver)) break;
else $this->robot->api['user_ids'] .= ', ';
}
} else if (is_string($receiver)) {
// Домен
// Инициализация пользователя
$this->robot->api['user_ids'] = $receiver;
}
if (isset($fields)) {
// Запрошены дополнительные запрашиваемые поля
// Инициализация дополнительных запрашиваемых полей
$this->robot->api['fields'] = '';
foreach ($fields as $key => $field) {
// Перебор дополнительных запрашиваемых полей
// Запись запрашиваемого дополнительного поля
$this->robot->api['fields'] .= $field;
// Запись разделителя
if ($key === array_key_last($fields)) break;
else $this->robot->api['fields'] .= ', ';
}
}
// Инициализация падежа
if (isset($name_case)) $this->robot->api['name_case'] = $name_case;
// Запрос
$request = json_decode($this->robot->browser->request('POST', 'users.get', ['form_params' => $this->robot->api->settings])->getBody()->getContents());
// Если в ответе ошибка
if (isset($request->error)) {
throw new Exception('ВКонтакте: ' . $request->error->error_msg, $request->error->error_code);
}
return is_array($receiver) ? $request->response : (isset($request->response[0]) ? $request->response[0] : null);
}
}

View File

@@ -17,11 +17,8 @@ use mirzaev\vk\robots\robot;
* @var array $settings Настройки
* @var float $version Версия API
*
* @todo
* 1. Создать __isset(), __unset()
*
* @package mirzaev\vk\api
* @author Arsen Mirzaev Tatyano-Muradovich <red@hood.su>
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*/
class settings implements ArrayAccess
{
@@ -30,7 +27,7 @@ class settings implements ArrayAccess
*
* Должна иметь тип string потому, что PHP при стандартных настройках удаляет нули у float
*/
protected const VK_API_VERSION_DEFAULT = '5.130';
protected const VK_API_VERSION_DEFAULT = '5.131';
/**
* Конструктор
@@ -145,36 +142,6 @@ class settings implements ArrayAccess
return $this;
}
/**
* Инициализация получателя
*
* @see mirzaev\vk\api\methods\messages Сообщения
*/
public function destination(string|array|int $target): self
{
if (is_int($target)) {
// Идентификатор
$this->settings['peer_id'] = $target;
return $this;
} else if (is_array($target)) {
// Идентификаторы
$this->settings['user_ids'] = $target;
return $this;
} else if (is_string($target)) {
// Домен
$this->settings['domain'] = $target;
return $this;
}
throw new Exception('Не удалось определить получателя', 500);
}
/**
* Записать свойство
*
@@ -206,20 +173,44 @@ class settings implements ArrayAccess
};
}
// public function __unset(string $name): void
// {
// match ($name) {
// 'settings' => throw new Exception('Запрещено удалять настройки', 500),
// 'robot' => throw new Exception('Запрещено удалять робота', 500),
// 'data', 'attachments' => $this->offsetUnset('attachments'),
// default => $this->offsetUnset($name)
// };
// }
/**
* Проверить инициализированность свойства
*
* @param string $name Название
*
* @return bool Свойство инициализировано?
*/
public function __isset(string $name): bool
{
return match ($name) {
'settings' => isset($this->settings),
'robot' => isset($this->robot),
'data', 'attachments' => $this->offsetExists('attachments'),
default => $this->offsetExists($name)
};
}
/**
* Деинициализированность свойство
*
* @param string $name Название
*
* @return void
*/
public function __unset(string $name): void
{
match ($name) {
'settings' => throw new Exception('Запрещено деинициализировать настройки', 500),
'robot' => throw new Exception('Запрещено деинициализировать робота', 500),
'data', 'attachments' => $this->offsetUnset('attachments'),
default => $this->offsetUnset($name)
};
}
/**
* Записать по смещению
*/
public function offsetSet(mixed $offset, mixed $value): mixed
public function offsetSet(mixed $offset, mixed $value): void
{
if (isset($this->settings)) {
if (strcasecmp($offset, 'settings') === 0) {
@@ -236,21 +227,27 @@ class settings implements ArrayAccess
if (is_array($value)) {
// Жесткая запись
return $this->settings['attachments'] = $value;
$this->settings['attachments'] = $value;
return;
}
if (empty($this->settings['attachments']) || count($this->settings['attachments']) < 10) {
// Записано менее чем 10 вложений (от 0 до 9)
// Запись (конкатенация)
return $this->settings['attachments'][] = $value;
$this->settings['attachments'][] = $value;
return;
}
throw new Exception('Превышено ограничение на 10 вложений', 500);
} else {
// Запись по ключу или смещению
return $this->settings[$offset] = $value;
$this->settings[$offset] = $value;
return;
}
}
@@ -260,7 +257,7 @@ class settings implements ArrayAccess
/**
* Прочитать по смещению
*/
public function &offsetGet(mixed $offset): mixed
public function offsetGet(mixed $offset): mixed
{
if (isset($this->settings)) {
if (strcasecmp($offset, 'settings') === 0) {
@@ -284,7 +281,11 @@ class settings implements ArrayAccess
}
/**
* Проверка существования смещения
* Проверить существование смещения
*
* @param mixed $offset Сдвиг
*
* @return bool Смещение существует?
*/
public function offsetExists(mixed $offset): bool
{

View File

@@ -24,7 +24,7 @@ use exception;
* @method public function get($id = null) Чтение из реестра
*
* @package mirzaev\vk
* @author Arsen Mirzaev Tatyano-Muradovich <red@hood.su>
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*/
final class core
{
@@ -45,22 +45,22 @@ final class core
*
* Используется в логировании
*/
private string $timezone;
private readonly string $timezone;
/**
* Путь до корня проекта
*/
private string $path_root;
private readonly string $path_root;
/**
* Путь до папки журналов
*/
private string $path_logs;
private readonly string $path_logs;
/**
* Путь до временной папки
*/
private string $path_temp;
private readonly string $path_temp;
/**
* Запись в журнал

View File

@@ -21,7 +21,7 @@ use mirzaev\vk\core,
* @see Jasny\ErrorHandler
*
* @package mirzaev\vk\loggers
* @author Arsen Mirzaev Tatyano-Muradovich <red@hood.su>
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*/
final class jasmo extends logger
{

View File

@@ -8,7 +8,7 @@ namespace mirzaev\vk\loggers;
* Абстрактный класс журналиста
*
* @package mirzaev\vk\loggers
* @author Arsen Mirzaev Tatyano-Muradovich <red@hood.su>
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*/
abstract class logger
{

View File

@@ -22,7 +22,7 @@ use mirzaev\vk\robots\robot,
* @method public function __isset($name) Проверка на инициализированность свойства
*
* @package mirzaev\vk\robots
* @author Arsen Mirzaev Tatyano-Muradovich <red@hood.su>
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*/
final class group extends robot
{
@@ -38,8 +38,8 @@ final class group extends robot
* @param string|null $key Ключ
*/
public function __construct(
protected int|null $id = null,
protected string|null $key = null
protected ?int $id = null,
protected ?string $key = null
) {
parent::__construct($id, $key);

View File

@@ -39,39 +39,39 @@ use GuzzleHttp\Client as browser;
* @method public function __toString() Конвертация в строку
*
* @package mirzaev\vk\robots
* @author Arsen Mirzaev Tatyano-Muradovich <red@hood.su>
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*/
abstract class robot
{
/**
* Сессия
* @var int $session Сессия
*/
protected int $session;
protected readonly int $session;
/**
* Аккаунт
* @var account $account Аккаунт ВКонтакте
*/
private account $account;
private readonly account $account;
/**
* $messages_mode Режим отправки сообщений
* @var api $api API ВКонтакте
*/
protected int $messages_mode = 1;
protected readonly api $api;
/**
* @var api API ВКонтакте
* @var browser $browser Браузер
*/
protected api $api;
protected readonly browser $browser;
/**
* Конструктор
*
* @param int|null $id Идентификатор
* @param string|null $key Ключ
* @param int|null $id Идентификатор робота
* @param string|null $key Ключ API ВКонтакте
*/
public function __construct(
protected int|null $id = null,
protected string|null $key = null
protected ?int $id = null,
protected ?string $key = null
) {
// Инициализация ядра
$core = core::init();
@@ -183,14 +183,13 @@ abstract class robot
public function __set(string $name, mixed $value): void
{
match ($name) {
'id' => isset($this->id) ? throw new Exception('Запрещено перезаписывать идентификатор', 500) : $this->id = (int) $value,
'session' => isset($this->session) ? throw new Exception('Запрещено перезаписывать сессию', 500) : $this->session = (int) $value,
'id' => empty($this->id) ?: $this->id = $value,
'session' => empty($this->session) ?: $this->session = $value,
'key' => $this->key((string) $value),
'account' => $this->account($value),
'api' => $this->api(),
'browser' => isset($this->browser) ? throw new Exception('Запрещено перезаписывать браузер', 500) : $this->browser = $value,
'messages_new' => $this->messages_new = (int) $value,
default => throw new Exception("Свойство $name не найдено", 404)
'browser' => empty($this->browser) ?: $this->browser = $value,
'messages_new' => $this->messages_new = (int) $value
};
}
@@ -219,23 +218,16 @@ abstract class robot
}
/**
* Проверить свойство на инициализированность
* Проверить на инициализированность
*
* @param string $name Название
*
* @return mixed
* @param mixed $name Название
*/
public function __isset(string $name): bool
{
return match ($name) {
'id' => isset($this->id),
'session' => isset($this->session),
'key' => isset($this->key),
'account' => isset($this->account),
'api' => isset($this->api),
'browser' => isset($this->browser),
'messages_new' => isset($this->messages_new),
default => throw new Exception("Свойство $name не найдено", 404)
default => false
};
}

View File

@@ -12,7 +12,7 @@ use mirzaev\accounts\vk as account;
* Робот-пользователь
*
* @package mirzaev\vk\robots
* @author Arsen Mirzaev Tatyano-Muradovich <red@hood.su>
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*/
final class user extends robot
{
@@ -23,8 +23,8 @@ final class user extends robot
* @param string|null $key Ключ
*/
public function __construct(
protected int|null $id = null,
protected string|null $key = null
protected readonly int|null $id = null,
protected readonly string|null $key = null
) {
parent::__construct($id, $key);