[*] мелкие корректировки

[+] Добавлено поле с ролями в geAllUserData
This commit is contained in:
rsgrinko committed 2022-08-04 19:24:07 +03:00
1 parent 1cc23d4eab
commit 20d24e23af
6 files changed
+93 -21

No files matched your search

+5
View File
@@ -59,6 +59,11 @@
*/
define('LOG_PATH', $_SERVER['DOCUMENT_ROOT'] . '/core/log');
/**
* Количество элементов на странице
*/
const PAGINATION_LIMIT = 10;
/**
* Параметры SQL базы
*/
+11 -1
View File
@@ -34,7 +34,17 @@
];
$userData = $USER ? $USER->getAllUserData() : '';
$userRoles = $USER ? $USER->getRolesObject()->getFullRoles() : '';
echo $twig->render('index.twig', ['navbarItems' => $navbarItems, 'name' => 'Roman Grinko', 'user' => $USER, 'userData' => $userData, 'userRoles' => $userRoles]);
echo $twig->render(
'index.twig',
[
'navbarItems' => $navbarItems,
'name' => $USER ? $USER->getName() : '',
'emailConfirmed' => $USER ? $USER->isEmailConfirmed() : false,
'user' => $USER,
'userData' => $userData,
'userRoles' => $userRoles
]
);
}
public static function test(int $id = 1)
+28 -5
View File
@@ -21,6 +21,7 @@
namespace Core\Models;
use Core\CoreException;
use Core\Helpers\Cache;
use Core\Models\User;
@@ -60,10 +61,11 @@
* Получение ролей пользователя
*
* @return array
* @throws CoreException
*/
public function getRoles(): array
{
$cacheId = md5('Roles_' . $this->user->getId() . '_getRoles');
$cacheId = md5(__CLASS__ . '::' . __FUNCTION__ . '_' . $this->user->getId());
if (Cache::check($cacheId)) {
$userRoles = Cache::get($cacheId);
} else {
@@ -88,10 +90,11 @@
* @param int $roleId ID роли
*
* @return int|null
* @throws CoreException
*/
public function addRole(int $roleId): ?int
{
$cacheId = md5('Roles_' . $this->user->getId() . '_getRoles');
$cacheId = md5(__CLASS__ . '::' . __FUNCTION__ . '_' . $this->user->getId());
Cache::delete($cacheId);
/** @var $DB DB */
@@ -105,10 +108,11 @@
* @param int $roleId ID роли
*
* @return int|null
* @throws CoreException
*/
public function deleteRole(int $roleId): ?int
{
$cacheId = md5('Roles_' . $this->user->getId() . '_getRoles');
$cacheId = md5(__CLASS__ . '::' . __FUNCTION__);
Cache::delete($cacheId);
/** @var $DB DB */
@@ -119,9 +123,11 @@
/**
* Получение полной информации о ролях пользователя
*
* @deprecated Реализован новый метод для получения этих данных
* @return array|null
* @throws CoreException
*/
public function getFullRoles(): ?array
public function getFullRolesOld(): ?array
{
return array_map(function ($element) {
return static::getAllRoles()[$element];
@@ -129,6 +135,23 @@
$this->getRoles());
}
/**
* Получение полной информации о ролях пользователя V2
*
* @return array|null
* @throws CoreException
*/
public function getFullRoles(): ?array
{
/** @var $DB DB */
$DB = DB::getInstance();
return $DB->query(
'SELECT ' . self::ROLES_TABLE . '.id, ' . self::ROLES_TABLE . '.name, ' . self::ROLES_TABLE . '.description FROM '
. self::USER_ROLES_TABLE . ' left JOIN ' . self::ROLES_TABLE . ' ON ' . self::USER_ROLES_TABLE . '.role_id = ' . self::ROLES_TABLE
. '.id WHERE ' . self::USER_ROLES_TABLE . '.user_id = "' . $this->user->getId() . '"'
) ?: [];
}
/**
* Получение всех существующих ролей
*
@@ -137,7 +160,7 @@
*/
public static function getAllRoles(): ?array
{
$cacheId = md5('Roles::getAllRoles');
$cacheId = md5(__CLASS__ . '::' . __FUNCTION__);
if (Cache::check($cacheId)) {
$roles = Cache::get($cacheId);
} else {
+33 -9
View File
@@ -93,6 +93,7 @@
* Получение аватара пользователя
*
* @return array|null
* @throws CoreException
*/
public function getImage(): ?array
{
@@ -113,6 +114,7 @@
* Получение всех полей пользователя
*
* @return array|null
* @throws CoreException
*/
public function getAllUserData(): ?array
{
@@ -121,6 +123,7 @@
$result = Cache::get($cacheId);
} else {
$result = (DB::getInstance())->getItem(self::TABLE, ['id' => $this->id]);
$result = array_merge($result, ['roles' => $this->getRolesObject()->getRoles()]);
Cache::set($cacheId, $result);
}
@@ -135,6 +138,7 @@
* Получение логина текущего пользователя
*
* @return string|null
* @throws CoreException
*/
public function getLogin(): ?string
{
@@ -145,6 +149,7 @@
* Получение E-Mail'а текущего пользователя
*
* @return string|null
* @throws CoreException
*/
public function getEmail(): ?string
{
@@ -155,6 +160,7 @@
* Получение имени текущего пользователя
*
* @return string|null
* @throws CoreException
*/
public function getName(): ?string
{
@@ -165,6 +171,7 @@
* Получение токена текущего пользователя
*
* @return string|null
* @throws CoreException
*/
public function getToken(): ?string
{
@@ -172,13 +179,14 @@
}
/**
* Получение времени ппоследней активности
* Получение времени последней активности
*
* @return string|null
* @throws CoreException
*/
public function getLastActive(): ?string
public function getLastActive(): ?int
{
return $this->getAllUserData() ? $this->getAllUserData()['last_active'] : null;
return $this->getAllUserData() ? (int)$this->getAllUserData()['last_active'] : null;
}
/**
@@ -188,13 +196,14 @@
*/
public function getId(): ?int
{
return $this->getAllUserData() ? $this->getAllUserData()['id'] : null;
return $this->id;
}
/**
* Получение кода верификации
*
* @return string|null
* @throws CoreException
*/
public function getVerificationCode(): ?string
{
@@ -362,10 +371,10 @@
'password' => self::passwordEncryption($password),
'name' => $name,
'image_id' => 0,
'token' => $verificationCode,
'token' => null,
'email' => $email,
'email_confirmed' => CODE_VALUE_N,
'verification_code' => md5(self::$cryptoSalt . $email . $login . time()),
'verification_code' => $verificationCode,
'last_active' => time(),
]);
$objectUser = null;
@@ -395,6 +404,14 @@
return $userId;
}
/**
* Обновление данных пользователя
*
* @param array $fields Массив полей для обновления
*
* @return bool
* @throws CoreException
*/
public function update(array $fields): bool
{
foreach($fields as $key => $value) {
@@ -439,13 +456,13 @@
}
/**
* Считает количество пользователей
* Получение количества пользователей
*
* @return int
*/
public static function countUsers(): int
public static function getAllCount(): int
{
$cacheId = md5('countUsers');
$cacheId = md5('User::getAllCount');
if (Cache::check($cacheId) && Cache::getAge($cacheId) < 300) {
$result = Cache::get($cacheId);
} else {
@@ -587,6 +604,7 @@
* Проверка на админа
*
* @return bool
* @throws CoreException
*/
public function isAdmin(): bool
{
@@ -670,6 +688,7 @@
* Проверка электронной почты на подтвержденность
*
* @return bool
* @throws CoreException
*/
public function isEmailConfirmed(): bool
{
@@ -700,9 +719,14 @@
* Отправка кода верификации пользователю на почту
*
* @return void
* @throws CoreException
*/
public function sendVerificationCode(): void
{
if (empty($this->getAllUserData()['verification_code'])) {
Log::logToFile('Ошибка отправки кода верификации: код отсутствует', 'User.log', ['userId' => $this->id]);
throw new CoreException('Ошибка отправки кода верификации: код отсутствует');
}
Log::logToFile('Выслан код верификаци', 'User.log', ['userId' => $this->id, 'code' => $this->getAllUserData()['verification_code']]);
$this->getMailObject()
->setSubject('Подтверждение E-Mail')