Исправление ошибок
This commit is contained in:
@@ -1,202 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace hood\vk\api;
|
||||
|
||||
use hood\vk\robots\robot;
|
||||
|
||||
use Throwable;
|
||||
use Exception;
|
||||
use ArrayAccess;
|
||||
use GuzzleHttp\Promise\Each;
|
||||
|
||||
/**
|
||||
* API ВКонтакте
|
||||
*
|
||||
* @var robot $robot Робот
|
||||
* @var array $settings Настройки
|
||||
* @var float $version Версия API
|
||||
*/
|
||||
class api implements ArrayAccess
|
||||
{
|
||||
/**
|
||||
* Конструктор
|
||||
*/
|
||||
public function __construct(
|
||||
protected robot $robot,
|
||||
protected array $settings = [],
|
||||
protected float $version = 5.124
|
||||
) {
|
||||
if (empty($settings)) {
|
||||
// Настройки не получены
|
||||
|
||||
// Инициализация
|
||||
$this->_init();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Инициализация (безопасная)
|
||||
*/
|
||||
public function init(): array
|
||||
{
|
||||
if (!isset($blocked)) {
|
||||
// Нет блокировки (запуск в первый раз)
|
||||
|
||||
// Блокировка
|
||||
static $blocked = true;
|
||||
|
||||
try {
|
||||
$this->_init();
|
||||
} catch (Throwable $t) {
|
||||
throw new Exception('Не удалось инициализировать API', $t->getCode(), $t->getPrevious());
|
||||
}
|
||||
}
|
||||
|
||||
return $this->settings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Реинициализация
|
||||
*/
|
||||
public function reinit(): array
|
||||
{
|
||||
// Реинициализация
|
||||
//unset($this->settings);
|
||||
$this->settings = [];
|
||||
|
||||
try {
|
||||
$this->_init();
|
||||
} catch (Throwable $t) {
|
||||
throw new Exception('Не удалось инициализировать API', $t->getCode(), $t->getPrevious());
|
||||
}
|
||||
|
||||
return $this->settings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Инициализация
|
||||
*/
|
||||
protected function _init(): void
|
||||
{
|
||||
// Ключ
|
||||
$this->settings['access_token'] = $this->robot->key;
|
||||
|
||||
// Версия API
|
||||
$this->settings['v'] = $this->version;
|
||||
}
|
||||
|
||||
/**
|
||||
* Выбрать получателя
|
||||
*
|
||||
* Определяет получателей по входным параметрам
|
||||
*
|
||||
* @see hood\vk\api\methods\messages Сообщения
|
||||
*/
|
||||
public function chooseDestination(string|array|int $destination): void
|
||||
{
|
||||
if (is_int($destination)) {
|
||||
// Идентификатор
|
||||
|
||||
$this->settings['peer_id'] = $destination;
|
||||
} else if (is_array($destination)) {
|
||||
// Идентификаторы
|
||||
|
||||
$this->settings['user_ids'] = $destination;
|
||||
} else {
|
||||
// Домен
|
||||
|
||||
$this->settings['domain'] = $destination;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Записать свойство
|
||||
*
|
||||
* @param string $name Название
|
||||
* @param mixed $value Значение
|
||||
*/
|
||||
public function __set(string $name, mixed $value): void
|
||||
{
|
||||
match ($name) {
|
||||
'settings' => !isset($this->settings) ? $this->settings = $value : throw new Exception('Запрещено перезаписывать настройки'),
|
||||
'robot' => !isset($this->robot) ? $this->robot = $value : throw new Exception('Запрещено перезаписывать Робота'),
|
||||
default => $this->settings[$name] = $value
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Прочитать свойство
|
||||
*
|
||||
* @param string $name Название
|
||||
*/
|
||||
public function __get(string $name): mixed
|
||||
{
|
||||
return match ($name) {
|
||||
'settings' => $this->settings ?? throw new Exception('Настройки не инициализированы'),
|
||||
'robot' => $this->robot,
|
||||
default => $this->settings[$name] ?? throw new Exception('Параметр не найден: settings[\'' . $name . '\']')
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Записать по смещению
|
||||
*/
|
||||
public function offsetSet(mixed $offset, mixed $value): void
|
||||
{
|
||||
if ($offset == 'settings') {
|
||||
!isset($this->settings) ? $this->settings = $value : throw new Exception('Запрещено перезаписывать настройки');
|
||||
} else if (isset($this->settings)) {
|
||||
$this->settings[$offset] = $value;
|
||||
} else {
|
||||
throw new Exception('Настройки не инициализированы');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Прочитать по смещению
|
||||
*/
|
||||
public function offsetGet(mixed $offset): mixed
|
||||
{
|
||||
if ($offset == 'settings' && isset($this->settings)) {
|
||||
return $this->settings;
|
||||
} else if (isset($this->settings)) {
|
||||
if (isset($this->settings[$offset])) {
|
||||
return $this->settings[$offset];
|
||||
} else {
|
||||
throw new Exception('Не найдено: settings[\'' . $offset . '\']');
|
||||
}
|
||||
} else {
|
||||
throw new Exception('Настройки не инициализированы');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверка существования смещения
|
||||
*/
|
||||
public function offsetExists(mixed $offset): bool
|
||||
{
|
||||
if ($offset == 'settings' && isset($this->settings)) {
|
||||
return isset($this->settings);
|
||||
} else if (isset($this->settings)) {
|
||||
return isset($this->settings[$offset]);
|
||||
} else {
|
||||
throw new Exception('Настройки не инициализированы');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Удалить по смещению
|
||||
*/
|
||||
public function offsetUnset(mixed $offset): void
|
||||
{
|
||||
if ($offset == 'settings' && isset($this->settings)) {
|
||||
unset($this->settings);
|
||||
} else if (isset($this->settings)) {
|
||||
unset($this->settings[$offset]);
|
||||
} else {
|
||||
throw new Exception('Настройки не инициализированы');
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,75 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace hood\vk\api;
|
||||
|
||||
use Exception;
|
||||
use hood\vk\robots\robot;
|
||||
|
||||
/**
|
||||
* Вложения
|
||||
*/
|
||||
class data
|
||||
{
|
||||
/**
|
||||
* @var array $data Вложения
|
||||
*/
|
||||
protected array $data = [];
|
||||
|
||||
/**
|
||||
* Конструктор
|
||||
*
|
||||
* @var robot $robot Робот
|
||||
*/
|
||||
public function __construct(
|
||||
protected robot $robot
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Записать вложения
|
||||
*
|
||||
* @param string|array $data Вложения
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
public function addData(...$data): self
|
||||
{
|
||||
// Если вложений больше 10
|
||||
if (count($this->data) + count($data) > 10) {
|
||||
throw new Exception('Превышен лимит вложений (10)');
|
||||
}
|
||||
|
||||
// Запись вложений
|
||||
$this->data = array_merge($this->data, $data);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Очистить вложения
|
||||
*/
|
||||
public function clear(): self
|
||||
{
|
||||
// Очистка вложений
|
||||
$this->data = [];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Прочитать свойство
|
||||
*
|
||||
* @param string $name Название
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function __get(string $name): mixed
|
||||
{
|
||||
return match ($name) {
|
||||
'data' => $this->data,
|
||||
default => throw new Exception('Свойство не найдено: ' . $name)
|
||||
};
|
||||
}
|
||||
}
|
@@ -27,46 +27,43 @@ use hood\vk\robots\group;
|
||||
final class messages extends method
|
||||
{
|
||||
/**
|
||||
* @param int $mode Режим отправки
|
||||
* @var int $mode Режим отправки
|
||||
*/
|
||||
protected int $mode = 1;
|
||||
|
||||
/**
|
||||
* @param string|null $text Текст
|
||||
* @var array[int] Сообщения для пересылки
|
||||
*/
|
||||
protected array $forward;
|
||||
|
||||
/**
|
||||
* @var data Вложения
|
||||
* @var int Сообщение для ответа
|
||||
*/
|
||||
protected data $data;
|
||||
protected int $reply;
|
||||
|
||||
/**
|
||||
* @var array Пересылаемые сообщения
|
||||
*/
|
||||
protected array $forwardMessages = [];
|
||||
|
||||
/**
|
||||
* @var int $ReplyMessage Ответное сообщение
|
||||
*/
|
||||
protected int $ReplyMessage;
|
||||
|
||||
/**
|
||||
* Создать сообщение
|
||||
* Конструктор
|
||||
*
|
||||
* @param robot $robot Робот
|
||||
* @param string|null $text Текст
|
||||
* @param int|string|array $destination = null
|
||||
*/
|
||||
public function __construct(
|
||||
protected robot $robot,
|
||||
protected string|null $text = null
|
||||
protected string|null $text = null,
|
||||
int|string|array $destination = null
|
||||
) {
|
||||
if (isset($this->text, $destination)) {
|
||||
// Быстрая отправка
|
||||
|
||||
$this->send($destination);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Записать текст
|
||||
*
|
||||
* @param string $text Текст
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
public function text(string $text): self
|
||||
{
|
||||
@@ -81,84 +78,27 @@ final class messages extends method
|
||||
}
|
||||
|
||||
/**
|
||||
* Записать пересылаемые сообщения
|
||||
*
|
||||
* @param $messageIds id пересылаемых сообщений
|
||||
*
|
||||
* @return self
|
||||
* Записать сообщения для пересылки
|
||||
*
|
||||
* @param $ids Идентификаторы сообщений
|
||||
*/
|
||||
public function forward(...$messageIds): self
|
||||
public function forward(...$ids): self
|
||||
{
|
||||
// Запись пересылаемых сообщений
|
||||
$this->forwardMessages = array_merge($this->forwardMessages, $messageIds);
|
||||
// Запись
|
||||
$this->forward = array_merge($this->forward ?? [], $ids);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Записать ответное сообщение
|
||||
*
|
||||
* @param $messageId id ответного сообщения
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
public function reply(int $messageId): self
|
||||
{
|
||||
// Запись ответного сообщения
|
||||
$this->ReplyMessage = $messageId;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Записать фото
|
||||
* Записать сообщение для ответа
|
||||
*
|
||||
* @param $img Фото
|
||||
*
|
||||
* @return self
|
||||
* @param $id Идентификатор сообщения
|
||||
*/
|
||||
public function image(...$pathPhoto): self
|
||||
public function reply(int $id): self
|
||||
{
|
||||
// Перебор фото
|
||||
foreach ($pathPhoto as $photo) {
|
||||
|
||||
// Загрузить фото
|
||||
$id = $this->robot->photo()->getPhoto($photo);
|
||||
|
||||
// Записать к вложениям
|
||||
$this->attachments($id);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Записать вложение
|
||||
*
|
||||
* @param $attachments Вложения
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
public function attachments(string ...$attachments): self
|
||||
{
|
||||
if (isset($this->data)) {
|
||||
// Если вложения инициализированны
|
||||
|
||||
// Записать вложение
|
||||
foreach ($attachments as $attachment) {
|
||||
$this->data->addData($attachment);
|
||||
}
|
||||
} else {
|
||||
// Если вложения не инициализированны
|
||||
|
||||
// Инициализация вложений
|
||||
$this->data = new data($this->robot);
|
||||
|
||||
// Записать вложение
|
||||
foreach ($attachments as $attachment) {
|
||||
$this->data->addData($attachment);
|
||||
}
|
||||
}
|
||||
// Запись
|
||||
$this->reply = $id;
|
||||
|
||||
return $this;
|
||||
}
|
||||
@@ -171,8 +111,10 @@ final class messages extends method
|
||||
* @see https://vk.com/dev/messages.send
|
||||
*
|
||||
* @return array Ответ сервера
|
||||
*
|
||||
* @todo Написать обработчик ошибок возвращаемых ВКонтакте
|
||||
*/
|
||||
public function send(int|string|array $destination): mixed
|
||||
public function send(int|string|array $destination): array
|
||||
{
|
||||
// Идентификатор
|
||||
$random_id = time();
|
||||
@@ -243,10 +185,6 @@ final class messages extends method
|
||||
$this->send($destination);
|
||||
}
|
||||
} else {
|
||||
// Что-то придумать :)
|
||||
// наверно throw new exception($request->error->error_msg)
|
||||
// А стоп. Ничего не нужно, просто возвращаем объект с ошибкой, где всё будет написано
|
||||
// Костя ты тупой?
|
||||
}
|
||||
}
|
||||
|
||||
@@ -264,8 +202,7 @@ final class messages extends method
|
||||
public function __set(string $name, mixed $value): void
|
||||
{
|
||||
match ($name) {
|
||||
'data' => !isset($this->data) ? $this->data->addData($value) : throw new Exception('Вложения не инициализированны'),
|
||||
default => throw new Exception('Свойство не найдено: ' . $name)
|
||||
default => throw new Exception("Свойство $name не найдено", 404)
|
||||
};
|
||||
}
|
||||
|
||||
@@ -280,16 +217,15 @@ final class messages extends method
|
||||
{
|
||||
return match ($name) {
|
||||
'text' => $this->text ?? throw new Exception('Текст не инициализирован'),
|
||||
'data' => isset($this->data) ? $this->data->data : throw new Exception('Вложения не инициализированны'),
|
||||
'forwardMessages' => !empty($this->forwardMessages) ? $this->forwardMessages : throw new Exception('Пересылаемые сообщения не инициализированны'),
|
||||
'ReplyMessage' => isset($this->ReplyMessage) ? $this->ReplyMessage : throw new Exception('Ответное сообщение не инициализированно'),
|
||||
default => throw new Exception('Свойство не найдено: ' . $name)
|
||||
'forward' => empty($this->forward) ? throw new Exception('Сообщения для пересылки не инициализированы') : $this->forward,
|
||||
'reply' => isset($this->reply) ? $this->reply : throw new Exception('Сообщение для ответа не инициализировано'),
|
||||
default => throw new Exception("Свойство $name не найдено", 404)
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить информацию о сообщении по id
|
||||
*
|
||||
*
|
||||
* @param string $message_ids Идентификатор сообщения
|
||||
*
|
||||
* @return object Информация о сообщении
|
||||
|
278
hood/vk/system/api/settings.php
Normal file
278
hood/vk/system/api/settings.php
Normal file
@@ -0,0 +1,278 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace hood\vk\api;
|
||||
|
||||
use hood\vk\robots\robot;
|
||||
|
||||
use Throwable;
|
||||
use Exception;
|
||||
use ArrayAccess;
|
||||
|
||||
/**
|
||||
* Настройки соединения с API
|
||||
*
|
||||
* @var robot $robot Робот
|
||||
* @var array $settings Настройки
|
||||
* @var float $version Версия API
|
||||
*
|
||||
* @todo
|
||||
* 1. Создать __isset(), __unset()
|
||||
*/
|
||||
class settings implements ArrayAccess
|
||||
{
|
||||
/**
|
||||
* Конструктор
|
||||
*/
|
||||
public function __construct(
|
||||
protected robot $robot,
|
||||
protected array $settings = []
|
||||
) {
|
||||
if (empty($settings)) {
|
||||
// Настройки не получены
|
||||
|
||||
// Инициализация
|
||||
$this->_init();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Инициализация (безопасная)
|
||||
*
|
||||
* @var float|null $version Версия API
|
||||
*/
|
||||
public function init(float|null $version = null): self
|
||||
{
|
||||
if (isset($blocked)) {
|
||||
// Блокировка найдена
|
||||
|
||||
throw new Exception('Повторная инициализация запрещена', 500);
|
||||
}
|
||||
|
||||
// Блокировка
|
||||
static $blocked = true;
|
||||
|
||||
// Инициализация
|
||||
try {
|
||||
$this->_init($version);
|
||||
} catch (Throwable $t) {
|
||||
throw new Exception('Не удалось инициализировать API', 500, $t->getPrevious());
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Реинициализация
|
||||
*
|
||||
* @var float|null $version Версия API
|
||||
*/
|
||||
public function reinit(float|null $version = null): self
|
||||
{
|
||||
// Буфер
|
||||
$version = $version ?? $this->settings['v'] ?? null;
|
||||
|
||||
// Деинициализация
|
||||
$this->settings = [];
|
||||
|
||||
// Инициализация
|
||||
try {
|
||||
$this->_init($version);
|
||||
} catch (Throwable $t) {
|
||||
throw new Exception('Не удалось инициализировать API', 500, $t->getPrevious());
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Инициализация
|
||||
*
|
||||
* @var float $version Версия API
|
||||
*/
|
||||
protected function _init(float $version = 5.124): self
|
||||
{
|
||||
// Ключ
|
||||
$this->settings['access_token'] = $this->robot->key;
|
||||
|
||||
// Версия API
|
||||
$this->settings['v'] = $version;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Записать получателя
|
||||
*
|
||||
* Определяет получателей по входным параметрам
|
||||
*
|
||||
* @see hood\vk\api\methods\messages Сообщения
|
||||
*/
|
||||
public function writeDestination(string|array|int $destination): void
|
||||
{
|
||||
if (is_int($destination)) {
|
||||
// Идентификатор
|
||||
|
||||
$this->settings['peer_id'] = $destination;
|
||||
} else if (is_array($destination)) {
|
||||
// Идентификаторы
|
||||
|
||||
$this->settings['user_ids'] = $destination;
|
||||
} else if (is_string($destination)) {
|
||||
// Домен
|
||||
|
||||
$this->settings['domain'] = $destination;
|
||||
}
|
||||
|
||||
throw new Exception('Не удалось определить получателя', 500);
|
||||
}
|
||||
|
||||
/**
|
||||
* Записать свойство
|
||||
*
|
||||
* @param string $name Название
|
||||
* @param mixed $value Значение
|
||||
*/
|
||||
public function __set(string $name, mixed $value): void
|
||||
{
|
||||
match ($name) {
|
||||
'settings' => isset($this->settings) ? throw new Exception('Запрещено перезаписывать настройки', 500) : $this->settings = $value,
|
||||
'robot' => isset($this->robot) ? throw new Exception('Запрещено перезаписывать Робота', 500) : $this->robot = $value,
|
||||
'data' => $this->offsetSet('data', $value),
|
||||
'attachments' => $this->offsetSet('attachments', $value),
|
||||
default => $this->offsetSet($name, $value)
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Прочитать свойство
|
||||
*
|
||||
* @param string $name Название
|
||||
*/
|
||||
public function __get(string $name): mixed
|
||||
{
|
||||
return match ($name) {
|
||||
'settings' => $this->settings ?? throw new Exception('Настройки не инициализированы', 500),
|
||||
'robot' => $this->robot ?? throw new Exception('Робот не инициализирован', 500),
|
||||
'data' => $this->offsetGet('data'),
|
||||
'attachments' => $this->offsetGet('attachments'),
|
||||
default => $this->offsetGet($name)
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Записать по смещению
|
||||
*/
|
||||
public function offsetSet(mixed $offset, mixed $value): mixed
|
||||
{
|
||||
if (isset($this->settings)) {
|
||||
if (strcasecmp($offset, 'settings') === 0) {
|
||||
// Полная запись
|
||||
|
||||
throw new Exception('Запрещено перезаписывать настройки', 500);
|
||||
} else if (
|
||||
(strcasecmp($offset, 'data') === 0)
|
||||
|| (strcasecmp($offset, 'attachment') === 0)
|
||||
|| (strcasecmp($offset, 'attachments') === 0)
|
||||
) {
|
||||
// Записать вложения
|
||||
|
||||
if (is_array($value)) {
|
||||
// Жесткая запись
|
||||
|
||||
return $this->settings['attachments'] = $value;
|
||||
}
|
||||
|
||||
// Конкатенация
|
||||
return $this->settings['attachments'][] = $value;
|
||||
} else {
|
||||
// Запись по ключу или смещению
|
||||
|
||||
return $this->settings[$offset] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception('Настройки не инициализированы', 500);
|
||||
}
|
||||
|
||||
/**
|
||||
* Прочитать по смещению
|
||||
*/
|
||||
public function &offsetGet(mixed $offset): mixed
|
||||
{
|
||||
if (isset($this->settings)) {
|
||||
if (strcasecmp($offset, 'settings') === 0) {
|
||||
// Полное чтение
|
||||
|
||||
return $this->settings;
|
||||
} else if (strcasecmp($offset, 'data') === 0 || strcasecmp($offset, 'attachments') === 0) {
|
||||
// Прочитать вложения
|
||||
|
||||
return $this->settings['attachments'];
|
||||
} else if (array_key_exists($offset, $this->settings)) {
|
||||
// Прочитать по ключу или смещению
|
||||
|
||||
return $this->settings[$offset];
|
||||
}
|
||||
|
||||
is_int($offset) ? throw new Exception("Смещение $offset не найдено", 404) : throw new Exception("Ключ $offset не найден", 404);
|
||||
}
|
||||
|
||||
throw new Exception('Настройки не инициализированы', 500);
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверка существования смещения
|
||||
*/
|
||||
public function offsetExists(mixed $offset): bool
|
||||
{
|
||||
if (isset($this->settings)) {
|
||||
if (strcasecmp($offset, 'settings') === 0) {
|
||||
// Полная проверка
|
||||
|
||||
return isset($this->settings);
|
||||
} else if (strcasecmp($offset, 'data') === 0 || strcasecmp($offset, 'attachments') === 0) {
|
||||
// Проверка вложений
|
||||
|
||||
return array_key_exists('attachments', $this->settings);
|
||||
} else {
|
||||
// Проверка по ключу или смещению
|
||||
|
||||
return array_key_exists($offset, $this->settings);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception('Настройки не инициализированы', 500);
|
||||
}
|
||||
|
||||
/**
|
||||
* Удалить по смещению
|
||||
*/
|
||||
public function offsetUnset(mixed $offset): void
|
||||
{
|
||||
if (isset($this->settings)) {
|
||||
if (strcasecmp($offset, 'settings') === 0) {
|
||||
// Полное удаление
|
||||
|
||||
unset($this->settings);
|
||||
|
||||
return;
|
||||
} else if (strcasecmp($offset, 'data') === 0 || strcasecmp($offset, 'attachments') === 0) {
|
||||
// Удаление вложений
|
||||
|
||||
unset($this->settings['attachments']);
|
||||
|
||||
return;
|
||||
} else {
|
||||
// Удаление по ключу или смещению
|
||||
|
||||
unset($this->settings[$offset]);
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception('Настройки не инициализированы', 500);
|
||||
}
|
||||
}
|
@@ -4,10 +4,11 @@ declare(strict_types=1);
|
||||
|
||||
namespace hood\vk;
|
||||
|
||||
use hood\vk\robots\robot;
|
||||
use hood\vk\traits\singleton;
|
||||
use hood\vk\loggers\jasmo;
|
||||
|
||||
use Exception;
|
||||
use hood\vk\loggers\jasmo,
|
||||
hood\vk\traits\singleton,
|
||||
hood\vk\robots\robot;
|
||||
|
||||
/**
|
||||
* Ядро
|
||||
@@ -23,13 +24,13 @@ use hood\vk\loggers\jasmo,
|
||||
* @method public function get($id = null) Чтение из реестра
|
||||
*
|
||||
* @package VK
|
||||
* @author Арсен Мирзаев <red@hood.su>
|
||||
* @author Арсен Мирзаев Татьяно-Мурадович <red@hood.su>
|
||||
*/
|
||||
final class core
|
||||
{
|
||||
use singleton;
|
||||
|
||||
/**
|
||||
/**
|
||||
* Счётчик роботов
|
||||
*
|
||||
* @var int
|
||||
@@ -101,15 +102,25 @@ final class core
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function set(int $id, robot $robot): void
|
||||
public function write(int $id, robot $robot): void
|
||||
{
|
||||
// if (empty($this->registry[$id])) {
|
||||
// // Если нет сессий, то инициализировать
|
||||
// $this->registry[$id] = [];
|
||||
// }
|
||||
try {
|
||||
// Инициализация уникального идентификатора сессии
|
||||
|
||||
// Создать новую сессию и обновить счётчик роботов
|
||||
$this->registry[$id][++$this->robots] = $robot;
|
||||
$session = count($this->read($id));
|
||||
} catch (Exception $e) {
|
||||
if ($e->getCode() === 404) {
|
||||
// Робота или сессии не существует
|
||||
|
||||
$session = 0;
|
||||
}
|
||||
} finally {
|
||||
// Записать новую сессию
|
||||
$this->registry[$id][$session] = $robot;
|
||||
|
||||
// Прединкрементация счётчика роботов
|
||||
++$this->robots;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -122,18 +133,35 @@ final class core
|
||||
*
|
||||
* @see hood\vk\traits\registry Модификация метода
|
||||
*
|
||||
* @return mixed
|
||||
* @return mixed Весь реестр, робота или сессию робота
|
||||
*/
|
||||
public function get(int|null $id = null, int|null $session = null): mixed
|
||||
public function read(int|null $id = null, int|null $session = null): mixed
|
||||
{
|
||||
if (isset($id) && array_key_exists($id, $this->registry)) {
|
||||
// Робот передан и найден
|
||||
if (isset($session) && array_key_exists($session, $this->registry[$id])) {
|
||||
// Сессия робота передана и найдена
|
||||
return $this->registry[$id][$session];
|
||||
if (isset($id)) {
|
||||
// Робот передан
|
||||
|
||||
if (array_key_exists($id, $this->registry)) {
|
||||
// Робот найден
|
||||
|
||||
if (isset($session)) {
|
||||
// Сессия робота передана
|
||||
|
||||
if (array_key_exists($session, $this->registry[$id])) {
|
||||
// Сессия робота найдена
|
||||
|
||||
return $this->registry[$id][$session];
|
||||
}
|
||||
|
||||
throw new Exception("Сессия $session робота с идентификатором $id не найдена", 404);
|
||||
}
|
||||
|
||||
return $this->registry[$id];
|
||||
} else {
|
||||
|
||||
throw new Exception("Робот с идентификатором $id не найден", 404);
|
||||
}
|
||||
return $this->registry[$id];
|
||||
}
|
||||
|
||||
return $this->registry;
|
||||
}
|
||||
|
||||
@@ -152,36 +180,40 @@ final class core
|
||||
if (isset($id)) {
|
||||
// Робот передан
|
||||
|
||||
if (!array_key_exists($id, $this->registry)) {
|
||||
throw new Exception('Робот не найден');
|
||||
}
|
||||
if (array_key_exists($id, $this->registry)) {
|
||||
// Робот найден
|
||||
|
||||
if (isset($session)) {
|
||||
// Сессия передана
|
||||
if (isset($session)) {
|
||||
// Сессия передана
|
||||
|
||||
if (!array_key_exists($session, $this->registry[$id])) {
|
||||
throw new Exception('Сессия не найдена');
|
||||
if (array_key_exists($session, $this->registry[$id])) {
|
||||
// Сессия найдена
|
||||
|
||||
// Постдекрементация счётчика роботов
|
||||
--$this->robots;
|
||||
|
||||
// Удаление сессии
|
||||
unset($this->registry[$id][$session]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Exception("Сессия $session робота с идентификатором $id не найдена", 404);
|
||||
}
|
||||
|
||||
// Счётчик роботов
|
||||
--$this->robots;
|
||||
// Вычитание из счётчика количества сессий робота
|
||||
$this->robots = $this->robots - count($this->registry[$id]);
|
||||
|
||||
// Удаление сессии
|
||||
unset($this->registry[$id][$session]);
|
||||
// Удаление робота и всех его сессий
|
||||
unset($this->registry[$id]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Счётчик роботов
|
||||
$this->robots = $this->robots - count($this->registry[$id]);
|
||||
|
||||
// Удаление робота и всех его сессий
|
||||
unset($this->registry[$id]);
|
||||
|
||||
return;
|
||||
throw new Exception("Робот с идентификатором $id не найден", 404);
|
||||
}
|
||||
|
||||
// Удаление всех роботов и их сессий
|
||||
// Полная очистка
|
||||
$this->registry = [];
|
||||
}
|
||||
|
||||
@@ -196,10 +228,10 @@ final class core
|
||||
public function __set(mixed $name, mixed $value): void
|
||||
{
|
||||
match ($name) {
|
||||
'timezone' => !isset($this->timezone) ? $this->timezone = $value : throw new Exception('Запрещено переопределять часовой пояс'),
|
||||
'path_root' => !isset($this->path_root) ? $this->path_root = $value : throw new Exception('Запрещено переопределять корневой каталог'),
|
||||
'path_logs' => !isset($this->path_logs) ? $this->path_logs = $value : throw new Exception('Запрещено переопределять каталог журналов'),
|
||||
'path_temp' => !isset($this->path_temp) ? $this->path_temp = $value : throw new Exception('Запрещено переопределять каталог временных файлов')
|
||||
'timezone' => !isset($this->timezone) ? $this->timezone = $value : throw new Exception('Запрещено переопределять часовой пояс', 500),
|
||||
'path_root' => !isset($this->path_root) ? $this->path_root = $value : throw new Exception('Запрещено переопределять корневой каталог', 500),
|
||||
'path_logs' => !isset($this->path_logs) ? $this->path_logs = $value : throw new Exception('Запрещено переопределять каталог журналов', 500),
|
||||
'path_temp' => !isset($this->path_temp) ? $this->path_temp = $value : throw new Exception('Запрещено переопределять каталог временных файлов', 500)
|
||||
};
|
||||
}
|
||||
|
||||
@@ -239,7 +271,7 @@ final class core
|
||||
// Если найден класс реализующий запрошенного робота
|
||||
return new $robot(...$params);
|
||||
} else {
|
||||
throw new Exception('Не найден робот: ' . $method);
|
||||
throw new Exception("Робот $method не найден", 404);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -4,11 +4,11 @@ declare(strict_types=1);
|
||||
|
||||
namespace hood\vk\robots;
|
||||
|
||||
use hood\vk\robots\robot,
|
||||
hood\vk\api\longpoll;
|
||||
use hood\vk\robots\robot;
|
||||
use hood\vk\api\longpoll;
|
||||
|
||||
use Throwable,
|
||||
Exception;
|
||||
use Throwable;
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* Робот-группа
|
||||
|
@@ -11,7 +11,7 @@ use GuzzleHttp\Client as browser;
|
||||
use hood\vk\core;
|
||||
use hood\vk\proxies\proxy;
|
||||
use hood\vk\captcha\captcha;
|
||||
use hood\vk\api\api;
|
||||
use hood\vk\api\settings as api;
|
||||
use hood\vk\api\methods\method;
|
||||
|
||||
use hood\accounts\vk as account;
|
||||
@@ -31,7 +31,7 @@ use hood\accounts\vk as account;
|
||||
*
|
||||
* @var int $messages_mode Режим отправки сообщений
|
||||
*
|
||||
* @method public function __construct(int $id = null, float $version = null) Конструктор
|
||||
* @method public function __construct(int $id = null) Конструктор
|
||||
* @method public function key(string $key) Инициализация ключа
|
||||
* @method public function account(account $account) Инициализация аккаунта
|
||||
* @method public function __set($name, $value) Запись свойства
|
||||
@@ -51,11 +51,6 @@ abstract class robot
|
||||
*/
|
||||
protected int $session;
|
||||
|
||||
/**
|
||||
* @var string Ключ
|
||||
*/
|
||||
protected string $key;
|
||||
|
||||
/**
|
||||
* @var string Аккаунт
|
||||
*/
|
||||
@@ -84,22 +79,24 @@ abstract class robot
|
||||
/**
|
||||
* Конструктор
|
||||
*
|
||||
* @param int $id Идентификатор
|
||||
* @param int|null $id Идентификатор
|
||||
* @param string|null $key Ключ
|
||||
*/
|
||||
public function __construct(
|
||||
protected int|null $id = null,
|
||||
protected string|null $key = null
|
||||
) {
|
||||
// Инициализация ядра
|
||||
$core = core::init();
|
||||
|
||||
// Идентификация робота
|
||||
$this->id = empty($id) ? $core->robots + 1 : $id;
|
||||
$this->id = $id ?? $core->robots + 1;
|
||||
|
||||
// Регистрация робота в ядре
|
||||
$core->set($this->id, $this);
|
||||
$core->write($this->id, $this);
|
||||
|
||||
// Идентификация сессии робота
|
||||
$this->session = count($core->get($this->id));
|
||||
$this->session = count($core->read($this->id));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -111,11 +108,7 @@ abstract class robot
|
||||
*/
|
||||
public function key(string $key): self
|
||||
{
|
||||
if (!isset($this->key)) {
|
||||
$this->key = $key;
|
||||
} else {
|
||||
throw new Exception('Запрещено перезаписывать ключ');
|
||||
}
|
||||
$this->__set('key', $key);
|
||||
|
||||
return $this;
|
||||
}
|
||||
@@ -129,11 +122,7 @@ abstract class robot
|
||||
*/
|
||||
public function account(account $account): self
|
||||
{
|
||||
if (!isset($this->account)) {
|
||||
$this->account = $account;
|
||||
} else {
|
||||
throw new Exception('Запрещено перезаписывать аккаунт');
|
||||
}
|
||||
$this->__set('account', $account);
|
||||
|
||||
return $this;
|
||||
}
|
||||
@@ -147,7 +136,7 @@ abstract class robot
|
||||
*/
|
||||
public function proxy(proxy $proxy): self
|
||||
{
|
||||
$this->proxy = $proxy;
|
||||
$this->__set('proxy', $proxy);
|
||||
|
||||
return $this;
|
||||
}
|
||||
@@ -161,7 +150,7 @@ abstract class robot
|
||||
*/
|
||||
public function captcha(captcha $captcha): self
|
||||
{
|
||||
$this->captcha = $captcha;
|
||||
$this->__set('captcha', $captcha);
|
||||
|
||||
return $this;
|
||||
}
|
||||
@@ -177,16 +166,16 @@ abstract class robot
|
||||
public function __set(string $name, mixed $value): void
|
||||
{
|
||||
match ($name) {
|
||||
'id' => !isset($this->id) ? $this->id = (int) $value : throw new Exception('Запрещено перезаписывать идентификатор'),
|
||||
'session' => !isset($this->session) ? $this->session = (int) $value : throw new Exception('Запрещено перезаписывать сессию'),
|
||||
'key' => !isset($this->key) ? $this->key = (string) $value : throw new Exception('Запрещено перезаписывать ключ'),
|
||||
'api' => !isset($this->api) ? $this->api = $value : throw new Exception('Запрещено перезаписывать API'),
|
||||
'account' => !isset($this->account) && $value instanceof account ? $this->account = $value : throw new Exception('Запрещено перезаписывать аккаунт'),
|
||||
'browser' => !isset($this->browser) && $value instanceof browser ? $this->browser = $value : throw new Exception('Запрещено перезаписывать браузер'),
|
||||
'id' => isset($this->id) ? throw new Exception('Запрещено перезаписывать идентификатор', 500) : $this->id = (int) $value,
|
||||
'session' => isset($this->session) ? throw new Exception('Запрещено перезаписывать сессию', 500) : $this->session = (int) $value,
|
||||
'key' => isset($this->key) ? throw new Exception('Запрещено перезаписывать ключ', 500) : $this->key = (string) $value,
|
||||
'api' => isset($this->api) ? throw new Exception('Запрещено перезаписывать API', 500) : $this->api = $value,
|
||||
'account' => isset($this->account) ? throw new Exception('Запрещено перезаписывать аккаунт', 500) : $this->account = $value,
|
||||
'browser' => isset($this->browser) ? throw new Exception('Запрещено перезаписывать браузер', 500) : $this->browser = $value,
|
||||
'proxy' => $this->proxy = $value,
|
||||
'captcha' => $this->captcha = $value,
|
||||
'messages_new' => $this->messages_new = (int) $value,
|
||||
default => throw new Exception('Свойство не найдено: ' . $name)
|
||||
default => throw new Exception("Свойство $name не найдено", 404)
|
||||
};
|
||||
}
|
||||
|
||||
@@ -200,11 +189,11 @@ abstract class robot
|
||||
public function __get(string $name): mixed
|
||||
{
|
||||
return match ($name) {
|
||||
'id' => $this->id ?? throw new Exception('Идентификатор не инициализирован'),
|
||||
'session' => $this->session ?? throw new Exception('Сессия не инициализирована'),
|
||||
'key' => $this->key ?? throw new Exception('Ключ не инициализирован'),
|
||||
'id' => $this->id ?? throw new Exception('Идентификатор не инициализирован', 500),
|
||||
'session' => $this->session ?? throw new Exception('Сессия не инициализирована', 500),
|
||||
'key' => $this->key ?? throw new Exception('Ключ не инициализирован', 500),
|
||||
'api' => $this->api ?? $this->api = new api($this),
|
||||
'account' => $this->account ?? throw new Exception('Аккаунт не инициализирован'),
|
||||
'account' => $this->account ?? throw new Exception('Аккаунт не инициализирован', 500),
|
||||
'browser' => $this->browser ?? $this->browser = new browser([
|
||||
'base_uri' => 'https://api.vk.com/method/',
|
||||
'cookies' => true
|
||||
@@ -212,7 +201,7 @@ abstract class robot
|
||||
'proxy' => $this->proxy,
|
||||
'captcha' => $this->captcha,
|
||||
'messages_new' => $this->messages_new,
|
||||
default => throw new Exception('Свойство не найдено: ' . $name)
|
||||
default => throw new Exception("Свойство $name не найдено", 404)
|
||||
};
|
||||
}
|
||||
|
||||
@@ -235,7 +224,7 @@ abstract class robot
|
||||
'proxy' => isset($this->proxy),
|
||||
'captcha' => isset($this->captcha),
|
||||
'messages_new' => isset($this->messages_new),
|
||||
default => throw new Exception('Свойство не найдено: ' . $name)
|
||||
default => throw new Exception("Свойство $name не найдено", 404)
|
||||
};
|
||||
}
|
||||
|
||||
@@ -257,7 +246,7 @@ abstract class robot
|
||||
return new $class($this, ...$params);
|
||||
}
|
||||
|
||||
throw new Exception('Метод не найден: ' . $method);
|
||||
throw new Exception("Метод $method не найден", 404);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -277,7 +266,7 @@ abstract class robot
|
||||
return $class(self, ...$params);
|
||||
}
|
||||
|
||||
throw new Exception('Метод не найден: ' . $method);
|
||||
throw new Exception("Метод $method не найден", 404);
|
||||
}
|
||||
|
||||
/**
|
||||
|
Reference in New Issue
Block a user