diff --git a/admin/phpcmd.php b/admin/phpcmd.php index b299391..1ea77a3 100644 --- a/admin/phpcmd.php +++ b/admin/phpcmd.php @@ -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 '

(ParseError) Ошибка парсинга: ' . $p->getMessage() . '

'; + } catch (CoreException $e) { + $e->showTrace(); + $e->showDetailTrace(); } catch (Throwable $e) { echo '

(Throwable) Ошибка при выполнении: ' . $e->getMessage() . '

'; - } catch (Error $e) { - echo '

(Error) Ошибка при выполнении: ' . $e->getMessage() - . '

'; } echo '

'; diff --git a/core/lib/Core/CoreException.class.php b/core/lib/Core/CoreException.class.php index 75f34d2..f6b8f8b 100644 --- a/core/lib/Core/CoreException.class.php +++ b/core/lib/Core/CoreException.class.php @@ -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 ''; } + + /** + * Отображение детального описания исключения + * + * @return void + */ + public function showDetailTrace(): void + { + $trace = $this->getTrace(); + echo '
'; + echo '' . $this->getMessage() . ''; + foreach ($trace as $k => $traceLine) { + if (file_exists($traceLine['file'])) { + echo '
'; + echo '
#' . $k . ' ' . $traceLine['file'] . ''; + echo SystemFunctions::getFilePreviewByLine(file_get_contents($traceLine['file']), $traceLine['line']); + echo '
'; + } + } + echo '
'; + } } diff --git a/core/lib/Core/DataBases/DB.class.php b/core/lib/Core/DataBases/DB.class.php index 602dfc3..1a7586b 100644 --- a/core/lib/Core/DataBases/DB.class.php +++ b/core/lib/Core/DataBases/DB.class.php @@ -306,7 +306,9 @@ . 'QUERY: ' . 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); } diff --git a/core/lib/Core/DataObjects/AbstractModel.class.php b/core/lib/Core/DataObjects/AbstractModel.class.php index dd806fa..aa16a7c 100644 --- a/core/lib/Core/DataObjects/AbstractModel.class.php +++ b/core/lib/Core/DataObjects/AbstractModel.class.php @@ -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; diff --git a/core/lib/Core/DataObjects/DataObjectsException.class.php b/core/lib/Core/DataObjects/DataObjectsException.class.php new file mode 100644 index 0000000..1ac734c --- /dev/null +++ b/core/lib/Core/DataObjects/DataObjectsException.class.php @@ -0,0 +1,31 @@ + + * 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 + { + + } \ No newline at end of file diff --git a/core/lib/Core/ExternalServices/ExternalServicesException.class.php b/core/lib/Core/ExternalServices/ExternalServicesException.class.php new file mode 100644 index 0000000..74db1c1 --- /dev/null +++ b/core/lib/Core/ExternalServices/ExternalServicesException.class.php @@ -0,0 +1,31 @@ + + * 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 + { + + } \ No newline at end of file diff --git a/core/lib/Core/ExternalServices/Request.class.php b/core/lib/Core/ExternalServices/Request.class.php index 897e5a3..68de230 100644 --- a/core/lib/Core/ExternalServices/Request.class.php +++ b/core/lib/Core/ExternalServices/Request.class.php @@ -146,7 +146,7 @@ private function sendRequest(): ?string { if (empty($this->url)) { - throw new CoreException('Адрес запроса не задан'); + throw new ExternalServicesException('Адрес запроса не задан'); } if ($this->usePostMethod === true) { diff --git a/core/lib/Core/ExternalServices/Telegram2.class.php b/core/lib/Core/ExternalServices/Telegram2.class.php index b879c27..bd53289 100644 --- a/core/lib/Core/ExternalServices/Telegram2.class.php +++ b/core/lib/Core/ExternalServices/Telegram2.class.php @@ -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; } diff --git a/core/lib/Core/Helpers/Cache/Cache.class.php b/core/lib/Core/Helpers/Cache/Cache.class.php new file mode 100644 index 0000000..c1c1f01 --- /dev/null +++ b/core/lib/Core/Helpers/Cache/Cache.class.php @@ -0,0 +1,77 @@ + + * 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) + { + + } + + } diff --git a/core/lib/Core/Helpers/Cache/MemCacheDriver.class.php b/core/lib/Core/Helpers/Cache/MemCacheDriver.class.php new file mode 100644 index 0000000..081cbc0 --- /dev/null +++ b/core/lib/Core/Helpers/Cache/MemCacheDriver.class.php @@ -0,0 +1,256 @@ + + * 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')); + } + }