[*] опеределан класс исключений

[*] мелкие правки
This commit is contained in:
rsgrinko committed 2023-05-23 22:49:28 +03:00
1 parent abe300ec42
commit ec2805efd5
10 files changed
+448 -12

No files matched your search

+4 -3
View File
@@ -19,6 +19,7 @@
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use Core\CoreException;
use Core\Models\{User, Roles};
require_once __DIR__ . '/inc/header.php';
@@ -167,12 +168,12 @@
} catch (ParseError $p) {
echo '<div class="alert alert-danger"><p><strong>(ParseError)</strong> Ошибка парсинга: ' . $p->getMessage()
. '</p></div>';
} catch (CoreException $e) {
$e->showTrace();
$e->showDetailTrace();
} catch (Throwable $e) {
echo '<div class="alert alert-danger"><p><strong>(Throwable)</strong> Ошибка при выполнении: ' . $e->getMessage()
. '</p></div>';
} catch (Error $e) {
echo '<div class="alert alert-danger"><p><strong>(Error)</strong> Ошибка при выполнении: ' . $e->getMessage()
. '</p></div>';
}
echo '</p>';
+37
View File
@@ -21,6 +21,8 @@
namespace Core;
use Core\Helpers\SystemFunctions;
class CoreException extends \Exception
{
/**
@@ -73,6 +75,20 @@
*/
const ERROR_SQL_QUERY = 600;
/**
* @param string|null $message Сообщение
* @param int $code Код исключения
*
* @throws self
*/
public function __construct($message = null, $code = 0)
{
if (!$message) {
throw new static('Неопознанное исключение: '. get_class($this));
}
parent::__construct($message, $code);
}
/**
* Возвращает обработанный callTrace текущего исключения
*
@@ -107,4 +123,25 @@
}
echo '</div>';
}
/**
* Отображение детального описания исключения
*
* @return void
*/
public function showDetailTrace(): void
{
$trace = $this->getTrace();
echo '<div class="showDetailTrace" style="font-size: 0.9em;">';
echo '<span style="padding: 10px;font-size: 1.2em;color: red;">' . $this->getMessage() . '</span>';
foreach ($trace as $k => $traceLine) {
if (file_exists($traceLine['file'])) {
echo '<div style="padding: 10px;border: 1px solid #c7c7c7;background: #f7f7f7;">';
echo '<div><span style="font-weight: bold;font-size: 1.16em;">#' . $k . ' ' . $traceLine['file'] . '</span>';
echo SystemFunctions::getFilePreviewByLine(file_get_contents($traceLine['file']), $traceLine['line']);
echo '</div></div>';
}
}
echo '</div>';
}
}
+3 -1
View File
@@ -306,7 +306,9 @@
. '<b>QUERY:</b> ' . PHP_EOL . $sql
);
if(DEBUG) {
throw new CoreException('В SQL запросе произошла ошибка. '.$this->db->errorInfo()[2].' Запрос: ' . $sql, CoreException::ERROR_SQL_QUERY);
throw new CoreException(
'В SQL запросе произошла ошибка: ' . $this->db->errorInfo()[2]
. '. Запрос: ' . $sql, CoreException::ERROR_SQL_QUERY);
}
throw new CoreException('В SQL запросе произошла ошибка', CoreException::ERROR_SQL_QUERY);
}
@@ -232,6 +232,7 @@
* @param bool $withoutNull Убирать значения с null
*
* @return array
* @throws \Exception
*/
private function getDataDifference(bool $withoutNull = false): array
{
@@ -375,32 +376,32 @@
switch ($columnsInfo[$key]['type']) {
case self::COLUMN_TYPE_ENUM:
if (in_array($value, $columnsInfo[$key]['enumValues'], true) === false) {
throw new CoreException('Недопустимое значение для enum поля ' . $key);
throw new DataObjectsException('Недопустимое значение для enum поля ' . $key);
}
$result[$key] = $value;
break;
case self::COLUMN_TYPE_BOOL:
if (is_bool($value) === false) {
throw new CoreException('Значение ' . $key . ' должно быть булевым');
throw new DataObjectsException('Значение ' . $key . ' должно быть булевым');
}
$result[$key] = $value;
break;
case self::COLUMN_TYPE_STRING:
if (is_string($value) === false) {
throw new CoreException('Значение ' . $key . ' должно быть строкой');
throw new DataObjectsException('Значение ' . $key . ' должно быть строкой');
}
$result[$key] = mb_substr($value, 0, $columnsInfo[$key]['length']);
break;
case self::COLUMN_TYPE_INT:
if (is_numeric($value) === false) {
throw new CoreException('Значение ' . $key . ' должно быть целочисленным числом');
throw new DataObjectsException('Значение ' . $key . ' должно быть целочисленным числом');
}
$result[$key] = (int)$value;
break;
case self::COLUMN_TYPE_DATETIME:
$date = strtotime($value);
if ($date === false) {
throw new CoreException($key . ' имеет некорректное значение даты');
throw new DataObjectsException($key . ' имеет некорректное значение даты');
}
$result[$key] = date(self::DATE_TIME_FORMAT, $date);
break;
@@ -408,7 +409,7 @@
try {
json_decode($value, false, 512, JSON_THROW_ON_ERROR);
} catch (Throwable $exception) {
throw new CoreException($key . ' содержит некорректный json');
throw new DataObjectsException($key . ' содержит некорректный json');
}
$result[$key] = $value;
break;
@@ -0,0 +1,31 @@
<?php
/**
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Core\DataObjects;
use Core\CoreException;
/**
* Класс исключений для DataObjects
*/
class DataObjectsException extends CoreException
{
}
@@ -0,0 +1,31 @@
<?php
/**
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Core\ExternalServices;
use Core\CoreException;
/**
* Класс исключений для ExternalServices
*/
class ExternalServicesException extends CoreException
{
}
@@ -146,7 +146,7 @@
private function sendRequest(): ?string
{
if (empty($this->url)) {
throw new CoreException('Адрес запроса не задан');
throw new ExternalServicesException('Адрес запроса не задан');
}
if ($this->usePostMethod === true) {
@@ -115,7 +115,7 @@
curl_close($ch);
$res = json_decode($res, true);
if (empty($res) || $res['ok'] !== true) {
throw new CoreException($res['description'], $res['error_code']);
throw new ExternalServicesException($res['description'], $res['error_code']);
}
return $res;
}
@@ -0,0 +1,77 @@
<?php
/**
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Core\Helpers\Cache;
/**
* Класс для кэширования данных и работы с кэшэм
*/
class Cache
{
/** @var string[] AVAILABLE_DRIVERS Поддерживаемые драйверы */
public const AVAILABLE_DRIVERS = [
'FileCacheDriver',
'MemCacheDriver',
];
/** @var string DEFAULT_DRIVER Драйвер по умолчанию */
public const DEFAULT_DRIVER = 'FileCacheDriver';
/** @var array|null $configParams Параметры */
private static ?array $configParams = null;
/** @var self|null $this|null $currentObject Объект текущего класса */
private static ?self $currentObject = null;
/** @var string|null $driver Драйвер */
private ?string $driver = null;
/**
* Инициализация кеша
*
* @param array $configParams Параметры
*
* @return void
*/
public static function init(array $configParams): void
{
self::$configParams = $configParams;
}
public static function getInstance(): self
{
if (self::$currentObject === null) {
self::$currentObject = new static(self::$configParams);
}
return self::$currentObject;
}
/**
* Конструктор
*
* @param array|null $configParams Параметры
*/
private function __construct(?array $configParams)
{
}
}
@@ -0,0 +1,256 @@
<?php
/**
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Core\Helpers\Cache;
use Core\Helpers\Кэшированные;
/**
* Класс для кэширования данных и работы с кэшэм
*/
class Cache
{
/**
* @var string $cacheDir Директория хранения файлов кэша
*/
private static string $cacheDir;
/**
* @var int $quantity Количество обращений к кэшу
*/
public static int $quantity = 0;
/**
* @var int $quantityRead Количество обращений к кэшу на чтение
*/
public static int $quantityRead = 0;
/**
* @var int $quantityWrite Количество обращений к кэшу на запись
*/
public static int $quantityWrite = 0;
/**
* @var bool $cacheEnabled Включает и выключает работу кэша
*/
private static bool $cacheEnabled = true;
/**
* Инициализация кэша
*
* @param string $dir Директория хранения файлов кэша
* @param bool $enabled Флаг включения кэширования
*/
public static function init(string $dir, $enabled = true): void
{
self::$cacheDir = $dir . '/';
self::$cacheEnabled = $enabled;
}
/**
* Получить количество обращений к кэшу
*
* @return int
*/
public function getCountAll(): int
{
return self::$quantity;
}
/**
* Получить количество чтений из кэша
*
* @return int
*/
public function getCountRead(): int
{
return self::$quantityRead;
}
/**
* Получить количество записи в кэш
*
* @return int
*/
public function getCountWrite(): int
{
return self::$quantityWrite;
}
/**
* Получение информации о кэше
*
* @return array
*/
public static function getCacheInfo(): array
{
return [
'countAll' => self::$quantity,
'countWrite' => self::$quantityWrite,
'countRead' => self::$quantityRead,
'cacheDir' => self::$cacheDir,
'cachedCount' => self::getCachedCount(),
'size' => self::getCacheSize(),
];
}
/**
* Проверка наличия элемента в кэше
*
* @param string $name Имя элемента кэша
*
* @return bool Флаг наличия или отсутствия кэша
*/
public static function check(string $name): bool
{
if (!self::$cacheEnabled
|| self::getAge($name) > CACHE_TTL
|| !file_exists(self::$cacheDir . md5($name) . '.tmp')) {
return false;
}
return true;
}
/**
* Получение кэшированных данных из кэша
*
* @param string $name Имя элемента кэша
*
* @return Кэшированные данные
*/
public static function get(string $name)
{
self::$quantity++;
self::$quantityRead++;
return unserialize(base64_decode(file_get_contents(self::$cacheDir . md5($name) . '.tmp')));
}
/**
* Получить количество кэшированных элементов
*
* @return int
*/
public static function getCachedCount()
{
return count(scandir(self::$cacheDir)) - 2;
}
/**
* Запись значения в кэш
*
* @param string $name Имя элемента кэша
* @param string|array|null $arValue Значение элемента кэша
*
* @return bool Флаг успешной или неудачной записи данных
*/
public static function set(string $name, $arValue): bool
{
if (!self::$cacheEnabled) {
return false;
}
self::$quantity++;
self::$quantityWrite++;
if (file_put_contents(self::$cacheDir . md5($name) . '.tmp', base64_encode(serialize($arValue)))) {
return true;
}
return false;
}
/**
* Полная очистка кэша
*
* @return bool Флаг успеха
*/
public static function flush(): bool
{
$di = new \RecursiveDirectoryIterator(self::$cacheDir, \FilesystemIterator::SKIP_DOTS);
$ri = new \RecursiveIteratorIterator($di, \RecursiveIteratorIterator::CHILD_FIRST);
foreach ($ri as $file) {
$file->isDir() ? rmdir($file) : unlink($file);
}
return true;
}
/**
* Удаление элемента из кэша
*
* @param string $name Имя элемента кэша
*
* @return bool Флаг успеха
*/
public static function delete(string $name): bool
{
if (self::check($name)) {
if (!unlink(self::$cacheDir . md5($name) . '.tmp')) {
self::$quantity++;
self::$quantityWrite++;
return false;
}
}
return true;
}
/**
* Получение размера элемента кэша в байтах
*
* @param string $name Имя элемента кэша
*
* @return int|null Размер элемента в байтах или null
*/
public static function getSize(string $name): ?int
{
if (self::check($name)) {
return filesize(self::$cacheDir . md5($name) . '.tmp');
}
return null;
}
/**
* Получение общего размера кэша в байтах
*
* @return int Размер кэша в байтах или false
*/
public static function getCacheSize(): int
{
$return_size = 0;
foreach (scandir(self::$cacheDir) as $file) {
if ($file === '.' || $file === '..') {
continue;
}
$return_size = $return_size + filesize(self::$cacheDir . $file);
}
return $return_size;
}
/**
* Получение времени существованя кэша в секундах
*
* @param string $name Имя элемента кэша
*
* @return int Время в секундах или false
*/
public static function getAge(string $name): int
{
return (time() - @filectime(self::$cacheDir . md5($name) . '.tmp'));
}
}