[+] новый метод алярма по проблемам

This commit is contained in:
rsgrinko committed 2023-10-28 15:17:34 +03:00
1 parent 9708ec5419
commit 0146815e2d
8 files changed
+139 -63

No files matched your search

+15 -21
View File
@@ -22,6 +22,7 @@
namespace Core\DataBases; namespace Core\DataBases;
use Core\CoreException; use Core\CoreException;
use Core\Helpers\SystemFunctions;
use Core\SystemConfig; use Core\SystemConfig;
use PDO; use PDO;
use Throwable; use Throwable;
@@ -113,22 +114,6 @@
// TODO: на случай чего то стоящего... // TODO: на случай чего то стоящего...
} }
/**
* Отправка уведомления о критическом событии
* // TODO: метод-заглушка для возможности оповещения о критических событиях
*
* @param string $text Текст
*
* @return void
* @deprecated Вероятно, будет выпилено в дальнейшем
*/
public static function sendAlarm(string $text): void
{
if (function_exists('sendTelegram')) {
sendTelegram($text);
}
}
/** /**
* Получить объект класса * Получить объект класса
* *
@@ -232,8 +217,14 @@
return $set; return $set;
} }
$set_string = ''; $set_string = '';
foreach ($set as $set_key => $set_item) { foreach ($set as $setKey => $setValue) {
$set_string .= ' ' . $set_key . '=\'' . $set_item . '\','; $set_string .= ' ' . $setKey . '=';
if (is_null($setValue)) {
$set_string .= ' ' . $setKey . '=null,';
} else {
$set_string .= '\'' . $setValue . '\',';
}
} }
return substr($set_string, 0, -1); return substr($set_string, 0, -1);
} }
@@ -302,9 +293,12 @@
try { try {
$stmt = $this->db->query($sql); $stmt = $this->db->query($sql);
} catch (\Throwable $t) { } catch (\Throwable $t) {
self::sendAlarm( SystemFunctions::sendAlarm('DataBase',
'<b><u>' . date('d.m.Y H:i:s') . '</u></b>' . PHP_EOL . '</b><b>SQL ERROR:</b> ' . PHP_EOL . $this->db->errorInfo()[2] . PHP_EOL '<b><u>' . date('d.m.Y H:i:s') . '</u></b>' . PHP_EOL
. '<b>QUERY:</b> ' . PHP_EOL . $sql . '</b><b>SQL ERROR:</b> ' . PHP_EOL
. $this->db->errorInfo()[2] . PHP_EOL
. '<b>QUERY:</b> ' . PHP_EOL
. $sql
); );
if(SystemConfig::getValue('DEBUG')) { if(SystemConfig::getValue('DEBUG')) {
throw new CoreException( throw new CoreException(
@@ -146,6 +146,7 @@
* @param string $table Таблица * @param string $table Таблица
* *
* @return array|null Имена колонок * @return array|null Имена колонок
* @throws Throwable
*/ */
private static function getColumnsInfo(string $table): array private static function getColumnsInfo(string $table): array
{ {
@@ -166,16 +167,16 @@
private function setData(array $data): void private function setData(array $data): void
{ {
$this->sourceData = $data; $this->sourceData = $data;
$columnsInfo = self::getColumnsInfo(static::TABLE);
foreach ($data as $prop => $value) { foreach ($data as $prop => $value) {
$key = $prop; $key = $prop;
if (empty($this->renameProps[$prop]) === false) { if (!empty($this->renameProps[$prop])) {
$key = $this->renameProps[$prop]; $key = $this->renameProps[$prop];
} }
if (property_exists($this, $key)) { if (property_exists($this, $key)) {
$this->$key = $value; $this->$key = $value;
} }
$columnsInfo = self::getColumnsInfo(static::TABLE); if (!empty($columnsInfo[$key])) {
if (empty($columnsInfo[$key]) === false) {
switch ($columnsInfo[$key]['type']) { switch ($columnsInfo[$key]['type']) {
case self::COLUMN_TYPE_BOOL: case self::COLUMN_TYPE_BOOL:
$this->$key = (bool)$this->$key; $this->$key = (bool)$this->$key;
@@ -188,23 +189,27 @@
/** /**
* Сохранить элемент * Сохранить элемент
* *
* @return $this * @return self
* @throws CoreException * @throws DataObjectsException
*/ */
public function save(): self public function save(): self
{ {
/** @var DB $db */ /** @var DB $db */
$db = DB::getInstance(); $db = DB::getInstance();
$id = static::ID_NAME; $id = static::ID_NAME;
if (empty($this->$id) === false) { try {
$diff = $this->getDataDifference(); if (!empty($this->$id)) {
if (empty($diff) === false) { $diff = $this->getDataDifference();
$db->update(static::TABLE, [$id => $this->$id], $this->sanitizeFields($diff)); if (!empty($diff)) {
$db->update(static::TABLE, [$id => $this->$id], $this->sanitizeFields($diff));
}
} else {
$this->$id = $db->addItem(static::TABLE, $this->sanitizeFields($this->getDataDifference(true)));
} }
} else { $this->setData($db->getItem(static::TABLE, [$id => $this->$id]));
$this->$id = $db->addItem(static::TABLE, $this->sanitizeFields($this->getDataDifference(true))); } catch (Throwable $e) {
throw new DataObjectsException('Произошла ошибка при сохранении данных: ' . $e->getMessage());
} }
$this->setData($db->getItem(static::TABLE, [$id => $this->$id]));
return $this; return $this;
} }
@@ -270,7 +275,7 @@
$renameList = array_flip($this->renameProps); $renameList = array_flip($this->renameProps);
} }
$columnList = self::getColumnsInfo(static::TABLE); $columnList = self::getColumnsInfo(static::TABLE);
foreach (self::getColumnsInfo(static::TABLE) as $prop => $info) { foreach ($columnList as $prop => $info) {
if (!$includeWriteProtected && in_array($prop, static::WRITE_PROTECTION, true)) { if (!$includeWriteProtected && in_array($prop, static::WRITE_PROTECTION, true)) {
continue; continue;
} }
@@ -315,7 +320,7 @@
public static function select(array $filter): ModelCollection public static function select(array $filter): ModelCollection
{ {
/** @var DB $db */ /** @var DB $db */
$db = DB::getInstance(); $db = DB::getInstance();
$result = $db->getItems(static::TABLE, $filter); $result = $db->getItems(static::TABLE, $filter);
$collectionClass = static::COLLECTION; $collectionClass = static::COLLECTION;
$collection = new $collectionClass(); $collection = new $collectionClass();
@@ -362,7 +367,7 @@
* @param array $array Входные данные * @param array $array Входные данные
* *
* @return array Результат * @return array Результат
* @throws CoreException * @throws DataObjectsException
*/ */
private function sanitizeFields(array $array): array private function sanitizeFields(array $array): array
{ {
+11 -10
View File
@@ -96,14 +96,15 @@
* *
* @param string $templateName Имя шаблона * @param string $templateName Имя шаблона
* *
* @return $this * @return self
*/ */
public function setTemplate(string $templateName): self public function setTemplate(string $templateName): self
{ {
if(!file_exists(MAIL_TEMPLATES_PATH . '/' . $templateName . '.html')) {
throw new CoreException('Шаблон "' . $templateName . '" не найден');
}
$this->templateName = $templateName; $this->templateName = $templateName;
if (!file_exists(MAIL_TEMPLATES_PATH . '/' . $templateName . '.html')) {
$this->templateName = 'default';
}
return $this; return $this;
} }
@@ -112,7 +113,7 @@
* *
* @param array $templateVars Массив переменных шаблона * @param array $templateVars Массив переменных шаблона
* *
* @return $this * @return self
*/ */
public function setTemplateVars(array $templateVars): self public function setTemplateVars(array $templateVars): self
{ {
@@ -137,7 +138,7 @@
/** /**
* От кого * От кого
* *
* @return $this * @return self
*/ */
public function setFrom($email, $name = null): self public function setFrom($email, $name = null): self
{ {
@@ -149,7 +150,7 @@
/** /**
* Кому * Кому
* *
* @return $this * @return self
*/ */
public function setTo($email, $name = null): self public function setTo($email, $name = null): self
{ {
@@ -161,7 +162,7 @@
/** /**
* Тема * Тема
* *
* @return $this * @return self
*/ */
public function setSubject($subject = null): self public function setSubject($subject = null): self
{ {
@@ -172,7 +173,7 @@
/** /**
* Тело письма * Тело письма
* *
* @return $this * @return self
*/ */
public function setBody($body = null): self public function setBody($body = null): self
{ {
@@ -183,7 +184,7 @@
/** /**
* Добавление файла к письму * Добавление файла к письму
* *
* @return $this * @return self
*/ */
public function addFile($filename): self public function addFile($filename): self
{ {
@@ -24,6 +24,8 @@
use Core\CoreException; use Core\CoreException;
use Core\DTO\System\Memory; use Core\DTO\System\Memory;
use Core\Models\Roles;
use Core\Models\User;
use Core\SystemConfig; use Core\SystemConfig;
/** /**
@@ -921,4 +923,28 @@
return $memoryObject; return $memoryObject;
} }
/**
* Отправка уведомления о критическом событии
*
* @param string $text Текст алярма
*
* @return void
*/
public static function sendAlarm(string $title, string $text): void
{
$userList = User::getListByRole(Roles::ALARM_ROLE_ID);
foreach($userList as $userObject) {
(new Mail())->setFrom(SERVER_EMAIL, SERVER_EMAIL_NAME)
->setTemplate(MAIL_TEMPLATE_DEFAULT)
->setTo($userObject->getEmail(), $userObject->getName())
->setSubject('Alarm: ' . $title)
->setBody($text)
->send();
}
if (function_exists('sendTelegram')) {
sendTelegram('<b>' . $title . '</b>' . PHP_EOL. $text);
}
}
} }
+6 -16
View File
@@ -62,6 +62,11 @@
*/ */
const USER_ROLE_ID = 5; const USER_ROLE_ID = 5;
/**
* Роль "уведомления о событиях"
*/
const ALARM_ROLE_ID = 6;
/** /**
* @var User $user * @var User $user
*/ */
@@ -125,7 +130,7 @@
* @return int|null * @return int|null
* @throws CoreException * @throws CoreException
*/ */
public function deleteRole(int $roleId): ?int public function delete(int $roleId): ?int
{ {
$cacheId = md5(__CLASS__ . '::' . __FUNCTION__); $cacheId = md5(__CLASS__ . '::' . __FUNCTION__);
Cache::delete($cacheId); Cache::delete($cacheId);
@@ -135,21 +140,6 @@
return $DB->query('DELETE FROM ' . self::USER_ROLES_TABLE . ' WHERE user_id=' . $this->user->getId() . ' AND role_id=' . $roleId); return $DB->query('DELETE FROM ' . self::USER_ROLES_TABLE . ' WHERE user_id=' . $this->user->getId() . ' AND role_id=' . $roleId);
} }
/**
* Получение полной информации о ролях пользователя
*
* @deprecated Реализован новый метод для получения этих данных
* @return array|null
* @throws CoreException
*/
public function getFullRolesOld(): ?array
{
return array_map(function ($element) {
return static::getAllRoles()[$element];
},
$this->getRoles());
}
/** /**
* Получение полной информации о ролях пользователя V2 * Получение полной информации о ролях пользователя V2
* *
+21
View File
@@ -28,6 +28,7 @@
use Core\CoreException; use Core\CoreException;
use Core\Helpers\{Cache, Log, Mail, Sanitize, SystemFunctions}; use Core\Helpers\{Cache, Log, Mail, Sanitize, SystemFunctions};
use Core\DataBases\DB; use Core\DataBases\DB;
use Core\DTO\User\FilterUser;
use Throwable; use Throwable;
class User class User
@@ -801,6 +802,26 @@
return SystemFunctions::arrayToXml($res, self::TABLE); return SystemFunctions::arrayToXml($res, self::TABLE);
} }
/**
* Выборка пользователей по роли
*
* @param int $roleId Идентификатор роли
*
* @return self[]
* @throws CoreException
*/
public static function getListByRole(int $roleId): array
{
$result = [];
/** @var $DB DB Объект базы данных */
$DB = DB::getInstance();
$res = $DB->getItems(Roles::USER_ROLES_TABLE, ['id' => $roleId]);
foreach ($res as $element) {
$result[] = new self((int)$element['user_id']);
}
return $result;
}
/** /**
* Проверка электронной почты на подтвержденность * Проверка электронной почты на подтвержденность
* *
+34 -1
View File
@@ -20,7 +20,7 @@
*/ */
/** /**
* Класс для работы с пользователями * Модель пользователя
*/ */
namespace Core\Models; namespace Core\Models;
@@ -36,6 +36,15 @@
/** @var string Имя */ /** @var string Имя */
protected $name; protected $name;
/** @var string $login Логин */
protected $login;
/** @var int $image_id Идентификатор картинки */
protected $image_id;
/** @var string $token Токен */
protected $token;
/** /**
* Получить имя * Получить имя
* *
@@ -59,4 +68,28 @@
return $this; return $this;
} }
/**
* Получить идентификатор изображения
*
* @return int|null
*/
public function getImageId(): ?int
{
return $this->image_id;
}
/**
* Установить идентификатор изображения
*
* @param int $id Идентификатор изображения
*
* @return $this
*/
public function setImageId(int $id): self
{
$this->image_id = $id;
return $this;
}
} }
+6
View File
@@ -41,6 +41,12 @@ final class Roles extends AbstractMigration
'date_created' => date('Y-m-d H:i:s'), 'date_created' => date('Y-m-d H:i:s'),
'date_updated' => null, 'date_updated' => null,
], ],
[
'name' => 'Уведомления о событиях',
'description' => 'Роль для рассылок уведомлений о сбоях в работе проекта',
'date_created' => date('Y-m-d H:i:s'),
'date_updated' => null,
],
]; ];
} }