[*] новые методы апи и фикс логирования изменения данных пользователя

This commit is contained in:
rsgrinko committed 2023-03-02 12:42:17 +03:00
1 parent 7b183b6c32
commit 02172c3586
6 files changed
+185 -3

No files matched your search

+1 -1
View File
@@ -141,7 +141,7 @@
/**
* Флаг использования логирования
*/
const USE_LOG = false;
const USE_LOG = true;
/**
* E-Mail сайта
+48
View File
@@ -34,9 +34,13 @@
/** @var User $userObject Объект пользователя */
private $userObject;
/** @var Request $request Объект запроса */
private $request;
public function __construct(User $userObject)
{
$this->userObject = $userObject;
$this->request = new Request();
}
/**
@@ -55,6 +59,50 @@
ApiView::output($result);
}
/**
* Получение информации о ролях текущего пользователя
*
* @return void
* @throws CoreException
* @throws \JsonException
*/
public function getUserRoles(): void
{
$result = $this->userObject->getRolesObject()->getFullRoles();
ApiView::output($result);
}
/**
* Отправка кода верификации
*
* @return void
* @throws CoreException
* @throws \JsonException
*/
public function sendVerificationCode(): void
{
$result = $this->userObject->sendVerificationCode();
ApiView::output($result);
}
/**
* Смена имени пользователя
*
* @return void
* @throws CoreException
* @throws \JsonException
* @throws ApiException
*/
public function changeName(): void
{
$name = $this->request->getProperty('name');
if (empty(trim($name))) {
throw new ApiException('Новое имя не может быть пустым', ApiException::ERROR_INPUT_DATA);
}
$this->userObject->update(['name' => $name]);
ApiView::output(true);
}
/**
* Тестовый метод (не требующий авторизации)
+4
View File
@@ -23,6 +23,10 @@
class ApiException extends \Exception
{
/** @var int ERROR_INPUT_DATA Ошибка входных данных */
const ERROR_INPUT_DATA = 10000;
/** @var int ERROR_TOKEN_UNDEFINED Токен не определен */
const ERROR_TOKEN_UNDEFINED = 10001;
+126
View File
@@ -0,0 +1,126 @@
<?php
namespace Core\Api;
/**
* Класс обработки запросов
*/
class Request
{
/** @var string Метод POST */
public const METHOD_POST = 'POST';
/** @var string Метод GET */
public const METHOD_GET = 'GET';
/** @var array Свойства запроса */
protected $properties = [];
/** @var string Тип запроса */
protected $method;
/**
* Конструктор
*/
public function __construct()
{
$this->init();
}
/**
* Получить строковое свойство
*
* @param string $key Имя свойства
*
* @return string|null Значение
*/
public function getProperty(string $key): ?string
{
if (is_string($this->properties[$key]) === false) {
return null;
}
return $this->properties[$key] ?? null;
}
/**
* Получить параметры запроса в виде массива
*
* @return array Данные
*/
public function getArray(): array
{
return $this->properties;
}
/**
* Получить свойство-массив
*
* @param string $key Имя свойства
*
* @return array|null Значение
*/
public function getArrayProperty(string $key): ?array
{
if (is_array($this->properties[$key]) === false) {
return null;
}
return $this->properties[$key] ?? null;
}
/**
* Проверка существования свойства
*
* @param string $key Имя свойство
*
* @return bool Результат проверки
*/
public function isSetProperty(string $key): bool
{
return !empty($this->properties[$key]);
}
/**
* Получить метод, которым был отправлен запрос
*
* @return string Метод, которым был отправлен запрос
*/
public function getRequestMethod(): string
{
return $this->method;
}
/**
* Инициализация объекта запроса
*/
protected function init(): void
{
$this->method = $_SERVER['REQUEST_METHOD'];
switch ($_SERVER['REQUEST_METHOD']) {
case self::METHOD_POST:
$this->setProperties($_POST);
break;
case self::METHOD_GET:
$this->setProperties($_GET);
break;
}
}
/**
* Установка свойств полей запроса
*
* @param array $array Входной массив данных
*/
private function setProperties(array $array): void
{
array_walk_recursive(
$array,
static function (&$input) {
$input = strip_tags(trim($input));
if($input === 'undefined') {
$input = null;
}
}
);
$this->properties = $array;
}
}
@@ -98,6 +98,7 @@
}
$oses = [
'Postman' => '/PostmanRuntime/i',
'iOS' => '/(iPhone)|(iPad)/i',
'Windows 3.11' => '/Win16/i',
'Windows 95' => '/(Windows 95)|(Win95)|(Windows_95)/i',
@@ -124,7 +125,7 @@
];
foreach ($oses as $os => $pattern) {
if (preg_match($pattern, $_SERVER['HTTP_USER_AGENT'])) {
if (@preg_match($pattern, $_SERVER['HTTP_USER_AGENT'])) {
return $os;
}
}
+4 -1
View File
@@ -450,10 +450,13 @@
$fields[$key] = Sanitize::sanitizeString($value);
}
$cacheId = md5('User_getAllUserData_' . $this->id);
foreach($fields as $key => $value) {
$beforeData[$key] = $this->getAllUserData()[$key];
}
/** @var $DB DB Объект базы данных */
$DB = DB::getInstance();
Log::logToFile(
'Данные пользователя изменены', 'User.log', ['userId' => $this->id, 'before' => $this->getAllUserData(), 'after' => func_get_args()]
'Данные пользователя изменены', 'User.log', ['userId' => $this->id, 'before' => $beforeData, 'after' => $fields]
);
Cache::delete($cacheId);
return $DB->update(self::TABLE, ['id' => $this->id], $fields);