diff --git a/core/lib/Core/DataBases/DB.class.php b/core/lib/Core/DataBases/DB.class.php
index 3177ab5..0f75a59 100644
--- a/core/lib/Core/DataBases/DB.class.php
+++ b/core/lib/Core/DataBases/DB.class.php
@@ -22,6 +22,7 @@
namespace Core\DataBases;
use Core\CoreException;
+ use Core\Helpers\SystemFunctions;
use Core\SystemConfig;
use PDO;
use Throwable;
@@ -113,22 +114,6 @@
// 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;
}
$set_string = '';
- foreach ($set as $set_key => $set_item) {
- $set_string .= ' ' . $set_key . '=\'' . $set_item . '\',';
+ foreach ($set as $setKey => $setValue) {
+ $set_string .= ' ' . $setKey . '=';
+ if (is_null($setValue)) {
+ $set_string .= ' ' . $setKey . '=null,';
+ } else {
+ $set_string .= '\'' . $setValue . '\',';
+ }
+
}
return substr($set_string, 0, -1);
}
@@ -302,9 +293,12 @@
try {
$stmt = $this->db->query($sql);
} catch (\Throwable $t) {
- self::sendAlarm(
- '' . date('d.m.Y H:i:s') . '' . PHP_EOL . 'SQL ERROR: ' . PHP_EOL . $this->db->errorInfo()[2] . PHP_EOL
- . 'QUERY: ' . PHP_EOL . $sql
+ SystemFunctions::sendAlarm('DataBase',
+ '' . date('d.m.Y H:i:s') . '' . PHP_EOL
+ . 'SQL ERROR: ' . PHP_EOL
+ . $this->db->errorInfo()[2] . PHP_EOL
+ . 'QUERY: ' . PHP_EOL
+ . $sql
);
if(SystemConfig::getValue('DEBUG')) {
throw new CoreException(
diff --git a/core/lib/Core/DataObjects/AbstractModel.class.php b/core/lib/Core/DataObjects/AbstractModel.class.php
index aa16a7c..1154d84 100644
--- a/core/lib/Core/DataObjects/AbstractModel.class.php
+++ b/core/lib/Core/DataObjects/AbstractModel.class.php
@@ -146,6 +146,7 @@
* @param string $table Таблица
*
* @return array|null Имена колонок
+ * @throws Throwable
*/
private static function getColumnsInfo(string $table): array
{
@@ -166,16 +167,16 @@
private function setData(array $data): void
{
$this->sourceData = $data;
+ $columnsInfo = self::getColumnsInfo(static::TABLE);
foreach ($data as $prop => $value) {
$key = $prop;
- if (empty($this->renameProps[$prop]) === false) {
+ if (!empty($this->renameProps[$prop])) {
$key = $this->renameProps[$prop];
}
if (property_exists($this, $key)) {
$this->$key = $value;
}
- $columnsInfo = self::getColumnsInfo(static::TABLE);
- if (empty($columnsInfo[$key]) === false) {
+ if (!empty($columnsInfo[$key])) {
switch ($columnsInfo[$key]['type']) {
case self::COLUMN_TYPE_BOOL:
$this->$key = (bool)$this->$key;
@@ -188,23 +189,27 @@
/**
* Сохранить элемент
*
- * @return $this
- * @throws CoreException
+ * @return self
+ * @throws DataObjectsException
*/
public function save(): self
{
/** @var DB $db */
$db = DB::getInstance();
$id = static::ID_NAME;
- if (empty($this->$id) === false) {
- $diff = $this->getDataDifference();
- if (empty($diff) === false) {
- $db->update(static::TABLE, [$id => $this->$id], $this->sanitizeFields($diff));
+ try {
+ if (!empty($this->$id)) {
+ $diff = $this->getDataDifference();
+ 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->$id = $db->addItem(static::TABLE, $this->sanitizeFields($this->getDataDifference(true)));
+ $this->setData($db->getItem(static::TABLE, [$id => $this->$id]));
+ } catch (Throwable $e) {
+ throw new DataObjectsException('Произошла ошибка при сохранении данных: ' . $e->getMessage());
}
- $this->setData($db->getItem(static::TABLE, [$id => $this->$id]));
return $this;
}
@@ -270,7 +275,7 @@
$renameList = array_flip($this->renameProps);
}
$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)) {
continue;
}
@@ -315,7 +320,7 @@
public static function select(array $filter): ModelCollection
{
/** @var DB $db */
- $db = DB::getInstance();
+ $db = DB::getInstance();
$result = $db->getItems(static::TABLE, $filter);
$collectionClass = static::COLLECTION;
$collection = new $collectionClass();
@@ -362,7 +367,7 @@
* @param array $array Входные данные
*
* @return array Результат
- * @throws CoreException
+ * @throws DataObjectsException
*/
private function sanitizeFields(array $array): array
{
diff --git a/core/lib/Core/Helpers/Mail.class.php b/core/lib/Core/Helpers/Mail.class.php
index 9621ce4..11abc5f 100644
--- a/core/lib/Core/Helpers/Mail.class.php
+++ b/core/lib/Core/Helpers/Mail.class.php
@@ -96,14 +96,15 @@
*
* @param string $templateName Имя шаблона
*
- * @return $this
+ * @return self
*/
public function setTemplate(string $templateName): self
{
- if(!file_exists(MAIL_TEMPLATES_PATH . '/' . $templateName . '.html')) {
- throw new CoreException('Шаблон "' . $templateName . '" не найден');
- }
$this->templateName = $templateName;
+ if (!file_exists(MAIL_TEMPLATES_PATH . '/' . $templateName . '.html')) {
+ $this->templateName = 'default';
+ }
+
return $this;
}
@@ -112,7 +113,7 @@
*
* @param array $templateVars Массив переменных шаблона
*
- * @return $this
+ * @return self
*/
public function setTemplateVars(array $templateVars): self
{
@@ -137,7 +138,7 @@
/**
* От кого
*
- * @return $this
+ * @return self
*/
public function setFrom($email, $name = null): self
{
@@ -149,7 +150,7 @@
/**
* Кому
*
- * @return $this
+ * @return self
*/
public function setTo($email, $name = null): self
{
@@ -161,7 +162,7 @@
/**
* Тема
*
- * @return $this
+ * @return self
*/
public function setSubject($subject = null): self
{
@@ -172,7 +173,7 @@
/**
* Тело письма
*
- * @return $this
+ * @return self
*/
public function setBody($body = null): self
{
@@ -183,7 +184,7 @@
/**
* Добавление файла к письму
*
- * @return $this
+ * @return self
*/
public function addFile($filename): self
{
diff --git a/core/lib/Core/Helpers/SystemFunctions.class.php b/core/lib/Core/Helpers/SystemFunctions.class.php
index 96e21f1..c83a835 100644
--- a/core/lib/Core/Helpers/SystemFunctions.class.php
+++ b/core/lib/Core/Helpers/SystemFunctions.class.php
@@ -24,6 +24,8 @@
use Core\CoreException;
use Core\DTO\System\Memory;
+ use Core\Models\Roles;
+ use Core\Models\User;
use Core\SystemConfig;
/**
@@ -921,4 +923,28 @@
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('' . $title . '' . PHP_EOL. $text);
+ }
+ }
}
diff --git a/core/lib/Core/Models/Roles.class.php b/core/lib/Core/Models/Roles.class.php
index 95d0814..8b1df18 100644
--- a/core/lib/Core/Models/Roles.class.php
+++ b/core/lib/Core/Models/Roles.class.php
@@ -62,6 +62,11 @@
*/
const USER_ROLE_ID = 5;
+ /**
+ * Роль "уведомления о событиях"
+ */
+ const ALARM_ROLE_ID = 6;
+
/**
* @var User $user
*/
@@ -125,7 +130,7 @@
* @return int|null
* @throws CoreException
*/
- public function deleteRole(int $roleId): ?int
+ public function delete(int $roleId): ?int
{
$cacheId = md5(__CLASS__ . '::' . __FUNCTION__);
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);
}
- /**
- * Получение полной информации о ролях пользователя
- *
- * @deprecated Реализован новый метод для получения этих данных
- * @return array|null
- * @throws CoreException
- */
- public function getFullRolesOld(): ?array
- {
- return array_map(function ($element) {
- return static::getAllRoles()[$element];
- },
- $this->getRoles());
- }
-
/**
* Получение полной информации о ролях пользователя V2
*
diff --git a/core/lib/Core/Models/User.class.php b/core/lib/Core/Models/User.class.php
index 694cc61..8bfad62 100644
--- a/core/lib/Core/Models/User.class.php
+++ b/core/lib/Core/Models/User.class.php
@@ -28,6 +28,7 @@
use Core\CoreException;
use Core\Helpers\{Cache, Log, Mail, Sanitize, SystemFunctions};
use Core\DataBases\DB;
+ use Core\DTO\User\FilterUser;
use Throwable;
class User
@@ -801,6 +802,26 @@
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;
+ }
+
/**
* Проверка электронной почты на подтвержденность
*
diff --git a/core/lib/Core/Models/UserModel.class.php b/core/lib/Core/Models/UserModel.class.php
index 4c2b529..638128f 100644
--- a/core/lib/Core/Models/UserModel.class.php
+++ b/core/lib/Core/Models/UserModel.class.php
@@ -20,7 +20,7 @@
*/
/**
- * Класс для работы с пользователями
+ * Модель пользователя
*/
namespace Core\Models;
@@ -36,6 +36,15 @@
/** @var string Имя */
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 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;
+ }
+
}
\ No newline at end of file
diff --git a/db/migrations/20230405185040_roles.php b/db/migrations/20230405185040_roles.php
index 5f156b0..fa1ed32 100644
--- a/db/migrations/20230405185040_roles.php
+++ b/db/migrations/20230405185040_roles.php
@@ -41,6 +41,12 @@ final class Roles extends AbstractMigration
'date_created' => date('Y-m-d H:i:s'),
'date_updated' => null,
],
+ [
+ 'name' => 'Уведомления о событиях',
+ 'description' => 'Роль для рассылок уведомлений о сбоях в работе проекта',
+ 'date_created' => date('Y-m-d H:i:s'),
+ 'date_updated' => null,
+ ],
];
}