From d180de4869baff49db6983382d259af28d2906f3 Mon Sep 17 00:00:00 2001 From: NaysKutzu Date: Thu, 25 Jul 2024 10:45:46 +0200 Subject: [PATCH] PUSH -> Fix Lint --- .github/workflows/lint.yml | 25 +- .php-cs-fixer.dist.php | 69 +++++ addons/Example/Example.php | 2 - api/System/logs.php | 5 +- api/User/login.php | 3 - app/Cli/Colors.php | 69 +---- app/Cli/Commands/Colors.php | 2 +- app/Cli/Commands/Command.php | 26 +- app/Cli/Commands/Configure.php | 56 ++-- app/Cli/Commands/Down.php | 11 +- app/Cli/Commands/Help.php | 12 +- app/Cli/Commands/Migrate.php | 29 +- app/Cli/Commands/Rebuild.php | 66 ++--- app/Cli/Commands/Up.php | 11 +- app/Cli/Kernel.php | 24 +- app/Database/MySQL.php | 156 +++++----- app/Database/MySQLCache.php | 34 +-- app/Database/Redis/Redis.php | 2 - .../exception/database/MySQLError.php | 7 +- .../exception/migration/NoMigrationsFound.php | 7 +- app/Handlers/ActivityHandler.php | 31 +- app/Handlers/AnnouncementHandler.php | 243 +++++++-------- app/Handlers/CacheHandler.php | 37 +-- app/Handlers/NotificationHandler.php | 138 ++++----- .../AnnouncementNotFoundException.php | 2 +- .../NotificationNotFoundException.php | 2 +- .../interfaces/AnnouncementSocial.php | 2 +- app/Kernel/Debugger.php | 103 +++---- app/Kernel/Encryption.php | 18 +- app/Kernel/Logger.php | 49 ++- app/Kernel/LoggerTypes.php | 2 +- app/Managers/ConfigManager.php | 49 ++- app/Managers/LanguageManager.php | 48 +-- app/Managers/Settings.php | 35 ++- app/Managers/SettingsManager.php | 30 +- app/Managers/SnowFlakeManager.php | 33 ++- .../exception/settings/NoMigrationsFound.php | 7 +- app/Plugins/Events/ActivityEvent.php | 1 - app/Plugins/Events/AnnouncementEvent.php | 1 + app/Plugins/Events/ApplicationEvent.php | 2 +- app/Plugins/Events/ConfigEvent.php | 1 - app/Plugins/Events/CronEvent.php | 1 - app/Plugins/Events/DatabaseEvent.php | 1 + app/Plugins/Events/EncryptionEvent.php | 1 - app/Plugins/Events/ExceptionEvent.php | 1 - app/Plugins/Events/LoggerEvent.php | 3 - app/Plugins/Events/NotificationEvent.php | 3 +- app/Plugins/Events/PermissionEvent.php | 1 - app/Plugins/Events/RendererEvent.php | 1 - app/Plugins/Events/RoleEvent.php | 1 - app/Plugins/Events/RouterEvent.php | 1 - app/Plugins/Events/SettingEvent.php | 2 - app/Plugins/Events/SnowFlakeEvent.php | 1 - app/Plugins/Events/UserEvent.php | 12 +- app/Plugins/PluginsEventHandler.php | 6 - app/Plugins/PluginsManager.php | 6 +- app/Roles/RolesDataHandler.php | 132 ++++----- app/Roles/RolesHelper.php | 11 +- app/Roles/RolesPermissionDataHandler.php | 142 +++++---- app/User/Exceptions/UserException.php | 8 +- app/User/UserDataHandler.php | 155 +++++----- app/User/UserHelper.php | 279 +++++++++--------- commands/core/cache/cacheprocess.php | 10 +- commands/core/cache/cachepurge.php | 10 +- commands/core/encryption/newkey.php | 20 +- composer.json | 2 +- cron/jobs/SettingsJob.php | 6 +- cron/jobs/cacheJob.php | 4 +- cron/runner.php | 19 +- install/install.php | 74 +++-- install/mysql.php | 30 +- lang/en_US.php | 12 +- migrate/config/1.php | 18 +- migrate/config/2.php | 2 +- migrate/config/3.php | 2 +- public/index.php | 79 +++-- routes/api/system.php | 2 +- routes/views/core.php | 16 +- routes/views/index.php | 8 +- tests/EncryptionTest.php | 21 +- 80 files changed, 1194 insertions(+), 1359 deletions(-) create mode 100755 .php-cs-fixer.dist.php diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 1506a63..2dc95f2 100755 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -4,7 +4,7 @@ on: [push, pull_request] permissions: contents: read - + jobs: lint: name: Lint @@ -25,25 +25,4 @@ jobs: run: composer install --no-interaction --no-progress --no-suggest --prefer-dist - name: PHP CS Fixer (APP) - run: vendor/bin/php-cs-fixer fix app --dry-run - - - name: PHP CS Fixer (Tests) - run: vendor/bin/php-cs-fixer fix tests --dry-run - - name: PHP CS Fixer (Routes) - run: vendor/bin/php-cs-fixer fix routes --dry-run - - name: PHP CS Fixer (Lang) - run: vendor/bin/php-cs-fixer fix lang --dry-run - - name: PHP CS Fixer (Cron) - run: vendor/bin/php-cs-fixer fix lang --dry-run - - name: PHP CS Fixer (API) - run: vendor/bin/php-cs-fixer fix api --dry-run - - name: PHP CS Fixer (Addons) - run: vendor/bin/php-cs-fixer fix addons --dry-run - - name: PHP CS Fixer (Commands) - run: vendor/bin/php-cs-fixer fix commands --dry-run - - name: PHP CS Fixer (Install) - run: vendor/bin/php-cs-fixer fix install --dry-run - - name: PHP CS Fixer (Public) - run: vendor/bin/php-cs-fixer fix public --dry-run - - name: PHP CS Fixer (Migrate) - run: vendor/bin/php-cs-fixer fix migrate --dry-run + run: vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.dist.php \ No newline at end of file diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php new file mode 100755 index 0000000..70eff4e --- /dev/null +++ b/.php-cs-fixer.dist.php @@ -0,0 +1,69 @@ +in(__DIR__) + ->exclude([ + 'vendor', + 'node_modules', + '.github', + '.vscode', + '.git', + 'docs', + 'caches', + 'devtools', + 'logs', + 'themes', + 'app/Handlers/interfaces' + ]) + ->notName(['_ide_helper*']); + +return (new Config()) + ->setRiskyAllowed(true) + ->setFinder($finder) + ->setRules([ + '@Symfony' => true, + '@PSR1' => true, + '@PSR2' => true, + '@PSR12' => true, + 'align_multiline_comment' => ['comment_type' => 'phpdocs_like'], + 'combine_consecutive_unsets' => true, + 'concat_space' => ['spacing' => 'one'], + 'heredoc_to_nowdoc' => true, + 'no_alias_functions' => true, + 'no_unreachable_default_argument_value' => true, + 'no_useless_return' => true, + 'ordered_imports' => [ + 'sort_algorithm' => 'length', + ], + 'phpdoc_align' => [ + 'align' => 'left', + 'tags' => [ + 'param', + 'property', + 'return', + 'throws', + 'type', + 'var', + ], + ], + 'random_api_migration' => true, + 'ternary_to_null_coalescing' => true, + 'yoda_style' => [ + 'equal' => false, + 'identical' => false, + 'less_and_greater' => false, + ], + ]); \ No newline at end of file diff --git a/addons/Example/Example.php b/addons/Example/Example.php index dc81f57..8c3c66c 100755 --- a/addons/Example/Example.php +++ b/addons/Example/Example.php @@ -1,10 +1,8 @@ Logger::getAllSortedByDate(LoggerTypes::OTHER, LoggerLevels::OTHER, 10) + api::OK('Showing you latest logs', [ + 'logs' => Logger::getAllSortedByDate(LoggerTypes::OTHER, LoggerLevels::OTHER, 10), ]); } diff --git a/api/User/login.php b/api/User/login.php index 14ea07c..b3ff88b 100755 --- a/api/User/login.php +++ b/api/User/login.php @@ -1,12 +1,9 @@ tryConnection($host, $port, $username, $password, $database) == true) { echo self::NewLine(); - echo self::translateColorsCode("&fConnection to the database was &asuccessful!&o"); + echo self::translateColorsCode('&fConnection to the database was &asuccessful!&o'); echo self::NewLine(); - echo self::translateColorsCode("&fSaving the configuration...&o"); - cfg::set("database", "host", $host); - cfg::set("database", "port", $port); - cfg::set("database", "username", $username); - cfg::set("database", "password", $password); - cfg::set("database", "name", $database); - echo self::translateColorsCode("&fConfiguration saved &asuccessfully!&o"); + echo self::translateColorsCode('&fSaving the configuration...&o'); + cfg::set('database', 'host', $host); + cfg::set('database', 'port', $port); + cfg::set('database', 'username', $username); + cfg::set('database', 'password', $password); + cfg::set('database', 'name', $database); + echo self::translateColorsCode('&fConfiguration saved &asuccessfully!&o'); } else { - echo self::translateColorsCode("&7Failed to connect to the database. &o&fPlease check the provided information."); + echo self::translateColorsCode('&7Failed to connect to the database. &o&fPlease check the provided information.'); } - } public static function configure(): void { - } } diff --git a/app/Cli/Commands/Down.php b/app/Cli/Commands/Down.php index 6eeb63e..4ffbd7e 100755 --- a/app/Cli/Commands/Down.php +++ b/app/Cli/Commands/Down.php @@ -10,12 +10,13 @@ class Down extends Command public static function execute(bool $isFrameworkCommand = false): void { - echo self::log_info("Marking the application as down..."); - if (cfg::get('app', 'maintenance') == "true" && cfg::get('app', 'maintenance') != "false") { - echo self::translateColorsCode("&aApplication &ris already in maintenance mode!"); + echo self::log_info('Marking the application as down...'); + if (cfg::get('app', 'maintenance') == 'true' && cfg::get('app', 'maintenance') != 'false') { + echo self::translateColorsCode('&aApplication &ris already in maintenance mode!'); + return; } - cfg::set('app', 'maintenance', "true"); - echo self::log_success("Application is now down!"); + cfg::set('app', 'maintenance', 'true'); + echo self::log_success('Application is now down!'); } } diff --git a/app/Cli/Commands/Help.php b/app/Cli/Commands/Help.php index 959a131..b8af13c 100755 --- a/app/Cli/Commands/Help.php +++ b/app/Cli/Commands/Help.php @@ -8,11 +8,11 @@ class Help extends Command public static function execute(bool $isFrameworkCommand = false): void { - echo self::log_info(""); - echo self::log_info("-----------------------"); - echo self::log_info("| Available commands: |"); - echo self::log_info("-----------------------"); - echo self::log_info(""); + echo self::log_info(''); + echo self::log_info('-----------------------'); + echo self::log_info('| Available commands: |'); + echo self::log_info('-----------------------'); + echo self::log_info(''); $commands = scandir(__DIR__); foreach ($commands as $command) { @@ -30,6 +30,6 @@ public static function execute(bool $isFrameworkCommand = false): void echo self::log_info("{$command} > {$reflectionClass->getProperty('description')->getValue()}"); } - echo self::log_info(""); + echo self::log_info(''); } } diff --git a/app/Cli/Commands/Migrate.php b/app/Cli/Commands/Migrate.php index e73d085..cfc0620 100755 --- a/app/Cli/Commands/Migrate.php +++ b/app/Cli/Commands/Migrate.php @@ -2,7 +2,6 @@ namespace MythicalSystemsFramework\Cli\Commands; -use Exception; use MythicalSystemsFramework\Database\MySQL; use MythicalSystemsFramework\Managers\Settings; @@ -12,47 +11,45 @@ class Migrate extends Command public static function execute(bool $isFrameworkCommand = false): void { - echo self::log_info(""); - echo self::log_info("&c1.&7 Migrate the database"); - echo self::log_info("&c2.&7 Migrate the config"); - echo self::log_info("&c3.&7 Exit"); - echo self::log_info(""); + echo self::log_info(''); + echo self::log_info('&c1.&7 Migrate the database'); + echo self::log_info('&c2.&7 Migrate the config'); + echo self::log_info('&c3.&7 Exit'); + echo self::log_info(''); - $option = readline("Select an option: "); + $option = readline('Select an option: '); switch ($option) { case '1': self::db(); break; case '2': - echo self::translateColorsCode("&cThis option is not available yet!&o"); + echo self::translateColorsCode('&cThis option is not available yet!&o'); break; case '3': self::exit(); break; default: - echo "Invalid option selected."; + echo 'Invalid option selected.'; break; } } - public static function db(): void { try { - self::log_info("Migrating the database..."); - self::log_info(""); + self::log_info('Migrating the database...'); + self::log_info(''); MySQL::migrate(true); Settings::migrate(true); - self::log_success("&rDatabase migrated &asuccessfully&r!"); + self::log_success('&rDatabase migrated &asuccessfully&r!'); self::exit(); - } catch (Exception $e) { - die("Failed to migrate the database: " . $e->getMessage() . ""); + } catch (\Exception $e) { + exit('Failed to migrate the database: ' . $e->getMessage() . ''); } } public static function cfg(): void { - } } diff --git a/app/Cli/Commands/Rebuild.php b/app/Cli/Commands/Rebuild.php index e74ea91..b907d96 100755 --- a/app/Cli/Commands/Rebuild.php +++ b/app/Cli/Commands/Rebuild.php @@ -2,25 +2,23 @@ namespace MythicalSystemsFramework\Cli\Commands; -use Exception; use MythicalSystemsFramework\Database\MySQL; -use MythicalSystemsFramework\Managers\ConfigManager as cfg; use MythicalSystemsFramework\Managers\Settings; -use PDO; -use PDOException; +use MythicalSystemsFramework\Managers\ConfigManager as cfg; class Rebuild extends Command { public static string $description = 'A command that can help if you want to rebuild the app!'; + public static function execute(bool $isFrameworkCommand = false): void { - echo self::log_info(""); - echo self::log_info("&c1.&7 Rebuild the database"); - echo self::log_info("&c2.&7 Rebuild the app"); - echo self::log_info("&c3.&7 Exit"); - echo self::log_info(""); + echo self::log_info(''); + echo self::log_info('&c1.&7 Rebuild the database'); + echo self::log_info('&c2.&7 Rebuild the app'); + echo self::log_info('&c3.&7 Exit'); + echo self::log_info(''); - $option = readline("Select an option: "); + $option = readline('Select an option: '); switch ($option) { case '1': @@ -33,7 +31,7 @@ public static function execute(bool $isFrameworkCommand = false): void self::exit(); break; default: - echo "Invalid option selected."; + echo 'Invalid option selected.'; break; } } @@ -42,15 +40,15 @@ public static function db(): void { try { $db = new MySQL(); - if ($db->tryConnection(cfg::get("database", "host"), cfg::get("database", "port"), cfg::get("database", "username"), cfg::get("database", "password"), cfg::get("database", "name")) == true) { - echo self::translateColorsCode("&o&fConnection to the database was &asuccessful!&o"); + if ($db->tryConnection(cfg::get('database', 'host'), cfg::get('database', 'port'), cfg::get('database', 'username'), cfg::get('database', 'password'), cfg::get('database', 'name')) == true) { + echo self::translateColorsCode('&o&fConnection to the database was &asuccessful!&o'); echo self::NewLine(); - echo self::translateColorsCode("&4&lWARNING: &fThis option will wipe the database. &o"); - echo self::translateColorsCode("&4&lWARNING: &fOnly use this function if you know what you are doing &o"); - echo self::translateColorsCode("&4&lWARNING: &fOnce you wipe the database there is no going back! &o"); + echo self::translateColorsCode('&4&lWARNING: &fThis option will wipe the database. &o'); + echo self::translateColorsCode('&4&lWARNING: &fOnly use this function if you know what you are doing &o'); + echo self::translateColorsCode('&4&lWARNING: &fOnce you wipe the database there is no going back! &o'); echo self::translateColorsCode("&4&lWARNING: &fPlease be careful and don't play around with commands! &o"); - echo self::translateColorsCode("&4&lWARNING: &fThere is no other message then this so keep in mind! &o"); - echo self::translateColorsCode("&4&lWARNING: &fDo you really want to wipe the database? (&ey&f/&en&f): "); + echo self::translateColorsCode('&4&lWARNING: &fThere is no other message then this so keep in mind! &o'); + echo self::translateColorsCode('&4&lWARNING: &fDo you really want to wipe the database? (&ey&f/&en&f): '); $confirm = readline(); if (strtolower($confirm) == 'y') { @@ -58,48 +56,48 @@ public static function db(): void $mysql = new MySQL(); $db = $mysql->connectPDO(); - $db->exec("SET FOREIGN_KEY_CHECKS = 0"); - $tables = $db->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN); + $db->exec('SET FOREIGN_KEY_CHECKS = 0'); + $tables = $db->query('SHOW TABLES')->fetchAll(\PDO::FETCH_COLUMN); foreach ($tables as $table) { $db->exec("DROP TABLE IF EXISTS $table"); } - $db->exec("SET FOREIGN_KEY_CHECKS = 1"); + $db->exec('SET FOREIGN_KEY_CHECKS = 1'); echo self::NewLine(); echo self::NewLine(); echo self::NewLine(); echo self::NewLine(); echo self::NewLine(); - echo self::translateColorsCode("&fDatabase wiped!!&o"); + echo self::translateColorsCode('&fDatabase wiped!!&o'); MySQL::migrate(true); Settings::migrate(true); echo self::NewLine(); - echo self::translateColorsCode("&fDatabase rebuilt!&o"); + echo self::translateColorsCode('&fDatabase rebuilt!&o'); echo self::translateColorsCode("&fLet's start by setting up your configuration!&o"); Configure::configure(); - } catch (PDOException $e) { - echo self::translateColorsCode("&fFailed to drop tables: &c" . $e->getMessage() . "&o"); + } catch (\PDOException $e) { + echo self::translateColorsCode('&fFailed to drop tables: &c' . $e->getMessage() . '&o'); echo self::NewLine(); } } else { - self::exit("&fExiting...&o"); + self::exit('&fExiting...&o'); } } else { - self::exit("&cFailed to connect to the database!&o"); + self::exit('&cFailed to connect to the database!&o'); } - } catch (Exception $e) { - self::exit("&cFailed to rebuild the database: &r" . $e->getMessage() . ""); + } catch (\Exception $e) { + self::exit('&cFailed to rebuild the database: &r' . $e->getMessage() . ''); } } public static function app(): void { try { - self::log_info("Rebuilding the app..."); - self::log_info(""); - self::log_success("&rApp rebuilt &asuccessfully&r!"); + self::log_info('Rebuilding the app...'); + self::log_info(''); + self::log_success('&rApp rebuilt &asuccessfully&r!'); self::exit(); - } catch (Exception $e) { - die("Failed to rebuild the app: " . $e->getMessage() . ""); + } catch (\Exception $e) { + exit('Failed to rebuild the app: ' . $e->getMessage() . ''); } } } diff --git a/app/Cli/Commands/Up.php b/app/Cli/Commands/Up.php index c2c93af..bd64b21 100755 --- a/app/Cli/Commands/Up.php +++ b/app/Cli/Commands/Up.php @@ -10,12 +10,13 @@ class Up extends Command public static function execute(bool $isFrameworkCommand = false): void { - echo self::log_info("&rMarking the application as up..."); - if (cfg::get('app', 'maintenance') == "false" && cfg::get('app', 'maintenance') != "true") { - echo self::translateColorsCode("&aApplication &ris already up!"); + echo self::log_info('&rMarking the application as up...'); + if (cfg::get('app', 'maintenance') == 'false' && cfg::get('app', 'maintenance') != 'true') { + echo self::translateColorsCode('&aApplication &ris already up!'); + return; } - cfg::set('app', 'maintenance', "false"); - echo self::log_success("Application is now &aup&r!"); + cfg::set('app', 'maintenance', 'false'); + echo self::log_success('Application is now &aup&r!'); } } diff --git a/app/Cli/Kernel.php b/app/Cli/Kernel.php index e0c5724..200f550 100755 --- a/app/Cli/Kernel.php +++ b/app/Cli/Kernel.php @@ -2,19 +2,15 @@ namespace MythicalSystemsFramework\Cli; -use Exception; -use ReflectionClass; - class Kernel extends Colors { /** * Executes the framework command with the specified command name. * - * @param string $commandName The name of the command to execute. + * @param string $commandName the name of the command to execute * - * @return void - * @throws Exception If the command file cannot be found, the command class does not exist, - * or the command class does not have 'name' or 'description' properties. + * @throws \Exception if the command file cannot be found, the command class does not exist, + * or the command class does not have 'name' or 'description' properties */ public static function executeFrameworkCommand(string $commandName): void { @@ -22,7 +18,7 @@ public static function executeFrameworkCommand(string $commandName): void $commandFile = __DIR__ . "/Commands/$commandName.php"; if (!file_exists($commandFile)) { - throw new Exception("Command not found!"); + throw new \Exception('Command not found!'); } require_once $commandFile; @@ -30,24 +26,22 @@ public static function executeFrameworkCommand(string $commandName): void $commandClass = "MythicalSystemsFramework\\Cli\\Commands\\$commandName"; if (!class_exists($commandClass)) { - throw new Exception("Command not found!"); + throw new \Exception('Command not found!'); } - $reflectionClass = new ReflectionClass($commandClass); + $reflectionClass = new \ReflectionClass($commandClass); if (!$reflectionClass->hasProperty('description')) { - throw new Exception("Command class '$commandClass' does not have 'name' or 'description' properties."); + throw new \Exception("Command class '$commandClass' does not have 'name' or 'description' properties."); } $commandClass::execute(true); - } + /** * Exit the CLI application. * - * @param string $message The message to display before exiting. - * - * @return void + * @param string $message the message to display before exiting */ public static function exit(string $message = '&7Application exited &asuccessfully&7!'): void { diff --git a/app/Database/MySQL.php b/app/Database/MySQL.php index ecee282..59630d4 100755 --- a/app/Database/MySQL.php +++ b/app/Database/MySQL.php @@ -2,60 +2,58 @@ namespace MythicalSystemsFramework\Database; +use PDO; +use mysqli; use MythicalSystemsFramework\Cli\Kernel; -use MythicalSystemsFramework\Database\exception\database\MySQLError; -use MythicalSystemsFramework\Database\exception\migration\NoMigrationsFound; -use MythicalSystemsFramework\Managers\ConfigManager as cfg; use MythicalSystemsFramework\Kernel\Logger; -use MythicalSystemsFramework\Kernel\LoggerLevels; use MythicalSystemsFramework\Kernel\LoggerTypes; -use PDO; -use PDOException; -use mysqli; -use Exception; +use MythicalSystemsFramework\Kernel\LoggerLevels; +use MythicalSystemsFramework\Managers\ConfigManager as cfg; +use MythicalSystemsFramework\Database\exception\database\MySQLError; +use MythicalSystemsFramework\Database\exception\migration\NoMigrationsFound; class MySQL { private static $connection; public static int $migrated_files_count; + /** * Connects to the database server using PDO. * - * @return PDO The PDO object representing the database connection. - * @throws PDOException If the connection to the database fails. + * @return \PDO the PDO object representing the database connection + * + * @throws \PDOException if the connection to the database fails */ - public function connectPDO(): PDO + public function connectPDO(): \PDO { - - $dsn = "mysql:host=" . cfg::get("database", "host") . ";dbname=" . cfg::get("database", "name") . ";port=" . cfg::get("database", "port") . ";charset=utf8mb4"; + $dsn = 'mysql:host=' . cfg::get('database', 'host') . ';dbname=' . cfg::get('database', 'name') . ';port=' . cfg::get('database', 'port') . ';charset=utf8mb4'; try { - $pdo = new PDO($dsn, cfg::get("database", "username"), cfg::get("database", "password")); - $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + $pdo = new \PDO($dsn, cfg::get('database', 'username'), cfg::get('database', 'password')); + $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); + return $pdo; - } catch (PDOException $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "Failed to connect to the database!"); - throw new PDOException("Failed to connect to the database: " . $e->getMessage()); + } catch (\PDOException $e) { + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, 'Failed to connect to the database!'); + throw new \PDOException('Failed to connect to the database: ' . $e->getMessage()); } } /** * Connects to the database server using MYSQLI. - * - * @return mysqli */ - public function connectMYSQLI(): mysqli + public function connectMYSQLI(): \mysqli { if (!isset(self::$connection)) { - self::$connection = new mysqli( - cfg::get("database", "host"), - cfg::get("database", "username"), - cfg::get("database", "password"), - cfg::get("database", "name"), - cfg::get("database", "port") + self::$connection = new \mysqli( + cfg::get('database', 'host'), + cfg::get('database', 'username'), + cfg::get('database', 'password'), + cfg::get('database', 'name'), + cfg::get('database', 'port') ); if (self::$connection->connect_error) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "Failed to connect to the database!"); + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, 'Failed to connect to the database!'); } } @@ -63,9 +61,7 @@ public function connectMYSQLI(): mysqli } /** - * Close a database connection if open - * - * @return void + * Close a database connection if open. */ public static function closeConnection(): void { @@ -84,18 +80,21 @@ public static function closeConnection(): void * @param string $password The password * @param string $database The database name * - * @return bool True if the connection is successful, false otherwise. - * @throws PDOException If the connection to the database fails. * + * @return bool true if the connection is successful, false otherwise + * + * @throws \PDOException If the connection to the database fails. * */ public function tryConnection(string $host, string|int $port, string $username, string $password, string $database): bool { try { - $dsn = "mysql:host=" . $host . ";dbname=" . $database . ";port=" . $port . ";charset=utf8mb4"; - $pdo = new PDO($dsn, $username, $password); - $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + $dsn = 'mysql:host=' . $host . ';dbname=' . $database . ';port=' . $port . ';charset=utf8mb4'; + $pdo = new \PDO($dsn, $username, $password); + $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); + return true; - } catch (PDOException $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "Failed to execute PDO query: " . $e); + } catch (\PDOException $e) { + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, 'Failed to execute PDO query: ' . $e); + return false; } } @@ -105,8 +104,6 @@ public function tryConnection(string $host, string|int $port, string $username, * * @param string $table The table name! * @param string $id The record id! - * - * @return void */ public function requestLock(string $table, string $id): void { @@ -117,22 +114,22 @@ public function requestLock(string $table, string $id): void $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); $stmt = $conn->prepare("UPDATE ? SET `locked` = 'true' WHERE `id` = ?;"); - $stmt->bind_param("si", $table, $id); + $stmt->bind_param('si', $table, $id); $stmt->execute(); $stmt->close(); - } catch (Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "Failed to lock table: " . $e); + } catch (\Exception $e) { + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, 'Failed to lock table: ' . $e); + return; } } + /** * Try to unlock a record. * Unlock a record so you can write and read it! * * @param string $table The table name! * @param string $id The id of the record! - * - * @return void */ public static function requestUnLock(string $table, string $id): void { @@ -143,21 +140,21 @@ public static function requestUnLock(string $table, string $id): void $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); $stmt = $conn->prepare("UPDATE ? SET `locked` = 'false' WHERE `id` = ?;"); - $stmt->bind_param("si", $table, $id); + $stmt->bind_param('si', $table, $id); $stmt->execute(); $stmt->close(); - } catch (Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "Failed to unlock table: " . $e); + } catch (\Exception $e) { + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, 'Failed to unlock table: ' . $e); + return; } } + /** * Get the lock status of a record. * * @param string $table The table name * @param string $id The id of the record - * - * @return bool */ public static function getLock(string $table, string $id): bool { @@ -167,42 +164,45 @@ public static function getLock(string $table, string $id): bool } $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $stmt = $conn->prepare("SELECT `locked` FROM ? WHERE `id` = ?;"); - $stmt->bind_param("si", $table, $id); + $stmt = $conn->prepare('SELECT `locked` FROM ? WHERE `id` = ?;'); + $stmt->bind_param('si', $table, $id); $stmt->execute(); $stmt->close(); - return $stmt->get_result()->fetch_assoc()["locked"]; - } catch (Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "Failed to get lock status: " . $e); + + return $stmt->get_result()->fetch_assoc()['locked']; + } catch (\Exception $e) { + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, 'Failed to get lock status: ' . $e); + return false; } } + /** * Does a table exist in the database? * * @param string $table The table name - * - * @return bool */ public static function doesTableExist(string $table): bool { try { $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $conn->query("SELECT * FROM " . mysqli_real_escape_string($conn, $table)); + $conn->query('SELECT * FROM ' . mysqli_real_escape_string($conn, $table)); + return true; - } catch (Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "Failed to check if table exists: " . $e); + } catch (\Exception $e) { + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, 'Failed to check if table exists: ' . $e); + return false; } } + /** * Does a record exist in the database? * * @param string $table Table name * @param string $search The term you want to search for (id) * @param string $term What the value should be (1) - * @return bool */ public static function doesRecordExist(string $table, string $search, string $term): bool { @@ -212,36 +212,35 @@ public static function doesRecordExist(string $table, string $search, string $te } $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $stmt = $conn->prepare("SELECT * FROM ? WHERE ? = ?;"); - $stmt->bind_param("sss", $table, $search, $term); + $stmt = $conn->prepare('SELECT * FROM ? WHERE ? = ?;'); + $stmt->bind_param('sss', $table, $search, $term); $stmt->execute(); $stmt->close(); + return true; - } catch (Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "Failed to check if record exists: " . $e); + } catch (\Exception $e) { + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, 'Failed to check if record exists: ' . $e); + return false; } } /** * Migrate the database. - * - * @return void */ public static function migrate(bool $isCli = false): void { try { - $mysql = new MySQL(); $db = $mysql->connectPDO(); - $db->exec(" + $db->exec(' CREATE TABLE IF NOT EXISTS framework_migrations ( id INT AUTO_INCREMENT PRIMARY KEY, script VARCHAR(255) NOT NULL, executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) - "); + '); $sqlFiles = glob(__DIR__ . '/../../migrate/database/*.sql'); @@ -249,6 +248,7 @@ public static function migrate(bool $isCli = false): void usort($sqlFiles, function ($a, $b) { $aDate = intval(basename($a, '.sql')); $bDate = intval(basename($b, '.sql')); + return $aDate - $bDate; }); @@ -257,40 +257,40 @@ public static function migrate(bool $isCli = false): void $fileName = basename($sqlFile); // Get only the file name - $stmt = $db->prepare("SELECT COUNT(*) FROM framework_migrations WHERE script = ?"); + $stmt = $db->prepare('SELECT COUNT(*) FROM framework_migrations WHERE script = ?'); $stmt->execute([$fileName]); $count = $stmt->fetchColumn(); if ($count == 0) { $db->exec($script); - $stmt = $db->prepare("INSERT INTO framework_migrations (script) VALUES (?)"); + $stmt = $db->prepare('INSERT INTO framework_migrations (script) VALUES (?)'); $stmt->execute([$fileName]); if ($isCli == true) { - echo Kernel::translateColorsCode("&fExecuted migration: &e" . $fileName . "&o"); + echo Kernel::translateColorsCode('&fExecuted migration: &e' . $fileName . '&o'); echo Kernel::NewLine(); } } else { if ($isCli == true) { - echo Kernel::translateColorsCode("&fSkipping migration: &e" . $fileName . " &f(&ealready executed&f)&o"); + echo Kernel::translateColorsCode('&fSkipping migration: &e' . $fileName . ' &f(&ealready executed&f)&o'); echo Kernel::NewLine(); } } } } else { if ($isCli == true) { - echo Kernel::translateColorsCode("&cNo migrations found!&o"); + echo Kernel::translateColorsCode('&cNo migrations found!&o'); echo Kernel::NewLine(); } else { throw new NoMigrationsFound(); } } - } catch (PDOException $e) { + } catch (\PDOException $e) { if ($isCli == true) { - echo Kernel::translateColorsCode("&cFailed to migrate the database: " . $e->getMessage() . "&o"); + echo Kernel::translateColorsCode('&cFailed to migrate the database: ' . $e->getMessage() . '&o'); echo Kernel::NewLine(); } else { - throw new MySQLError("Failed to migrate the database: " . $e->getMessage()); + throw new MySQLError('Failed to migrate the database: ' . $e->getMessage()); } } } diff --git a/app/Database/MySQLCache.php b/app/Database/MySQLCache.php index aac2c35..e2816b9 100755 --- a/app/Database/MySQLCache.php +++ b/app/Database/MySQLCache.php @@ -2,8 +2,6 @@ namespace MythicalSystemsFramework\Database; -use Exception; -use MythicalSystems\Api\Api; use MythicalSystemsFramework\Managers\Settings; class MySQLCache extends MySQL @@ -12,28 +10,28 @@ public static function saveCache(string $table_name): void { try { if (self::doesTableExist($table_name) == false) { - throw new Exception("Table does not exist."); + throw new \Exception('Table does not exist.'); } $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $query = "SELECT * FROM " . mysqli_real_escape_string($conn, $table_name); + $query = 'SELECT * FROM ' . mysqli_real_escape_string($conn, $table_name); $result = $conn->query($query); if ($result->num_rows == 0) { - throw new Exception("No data found."); + throw new \Exception('No data found.'); } - /** + /* * Specific table dump settings! * * @requires framework_settings */ - if ($table_name == "framework_settings") { + if ($table_name == 'framework_settings') { /** * Code to export the settings file in a format that MythicalSystemsFramework\Managers\Settings can read! */ - $query = "SELECT scategory FROM " . mysqli_real_escape_string($conn, $table_name); + $query = 'SELECT scategory FROM ' . mysqli_real_escape_string($conn, $table_name); $result = $conn->query($query); if ($result->num_rows > 0) { @@ -50,7 +48,7 @@ public static function saveCache(string $table_name): void if ($category !== 0) { $data[$category] = []; - $query = "SELECT skey, svalue FROM " . mysqli_real_escape_string($conn, $table_name) . " WHERE scategory = '" . mysqli_real_escape_string($conn, $category) . "'"; + $query = 'SELECT skey, svalue FROM ' . mysqli_real_escape_string($conn, $table_name) . " WHERE scategory = '" . mysqli_real_escape_string($conn, $category) . "'"; $result = $conn->query($query); if ($result->num_rows > 0) { @@ -62,24 +60,22 @@ public static function saveCache(string $table_name): void } } } - - } elseif ($table_name == "framework_users") { - + } elseif ($table_name == 'framework_users') { } else { - throw new Exception("Table not supported."); + throw new \Exception('Table not supported.'); } - $cache_info["cache_info"] = [ - "table" => $table_name, - "date_created" => date("Y-m-d H:i:s"), - "date_expire" => date("Y-m-d H:i:s", strtotime("+".$data["caches"]["settings_cache_life"]." seconds")), + $cache_info['cache_info'] = [ + 'table' => $table_name, + 'date_created' => date('Y-m-d H:i:s'), + 'date_expire' => date('Y-m-d H:i:s', strtotime('+' . $data['caches']['settings_cache_life'] . ' seconds')), ]; $data = array_merge($cache_info, $data); $json = json_encode($data, JSON_PRETTY_PRINT); Settings::up(); file_put_contents(Settings::$cache_path . '/' . $table_name . '.json', $json); - } catch (Exception $e) { - throw new Exception("Failed to save cache: " . $e); + } catch (\Exception $e) { + throw new \Exception('Failed to save cache: ' . $e); } } diff --git a/app/Database/Redis/Redis.php b/app/Database/Redis/Redis.php index 59c5082..57545f8 100755 --- a/app/Database/Redis/Redis.php +++ b/app/Database/Redis/Redis.php @@ -6,7 +6,5 @@ class Redis { public static function getConnection() { - - } } diff --git a/app/Database/exception/database/MySQLError.php b/app/Database/exception/database/MySQLError.php index 17213bd..cada530 100755 --- a/app/Database/exception/database/MySQLError.php +++ b/app/Database/exception/database/MySQLError.php @@ -2,12 +2,9 @@ namespace MythicalSystemsFramework\Database\exception\database; -use Exception; -use Throwable; - -class MySQLError extends Exception +class MySQLError extends \Exception { - public function __construct($message = "MySQL Error.", $code = 0, Exception $previous = null) + public function __construct($message = 'MySQL Error.', $code = 0, ?\Exception $previous = null) { parent::__construct($message, $code, $previous); } diff --git a/app/Database/exception/migration/NoMigrationsFound.php b/app/Database/exception/migration/NoMigrationsFound.php index cc79bca..773781c 100755 --- a/app/Database/exception/migration/NoMigrationsFound.php +++ b/app/Database/exception/migration/NoMigrationsFound.php @@ -2,12 +2,9 @@ namespace MythicalSystemsFramework\Database\exception\migration; -use Exception; -use Throwable; - -class NoMigrationsFound extends Exception +class NoMigrationsFound extends \Exception { - public function __construct($message = "No migration not found.", $code = 0, Exception $previous = null) + public function __construct($message = 'No migration not found.', $code = 0, ?\Exception $previous = null) { parent::__construct($message, $code, $previous); } diff --git a/app/Handlers/ActivityHandler.php b/app/Handlers/ActivityHandler.php index 695045c..57492c8 100755 --- a/app/Handlers/ActivityHandler.php +++ b/app/Handlers/ActivityHandler.php @@ -9,11 +9,11 @@ class ActivityHandler /** * Adds a new activity to the database. * - * @param string $userId The user ID. - * @param string $username The username. - * @param string $description The activity description. - * @param string $ipv4 The user ip. - * @param string $action The action. + * @param string $userId the user ID + * @param string $username the username + * @param string $description the activity description + * @param string $ipv4 the user ip + * @param string $action the action */ public static function addActivity(string $userId, string $username, string $description, string $ipv4, string $action): void { @@ -22,8 +22,8 @@ public static function addActivity(string $userId, string $username, string $des $time = date('Y-m-d H:i:s'); - $stmt = $conn->prepare("INSERT INTO framework_users_activities (user_id, username, description, action, ip_address, date) VALUES (?, ?, ?, ?, ?, ?)"); - $stmt->bind_param("ssssss", $userId, $username, $description, $action, $ipv4, $time); + $stmt = $conn->prepare('INSERT INTO framework_users_activities (user_id, username, description, action, ip_address, date) VALUES (?, ?, ?, ?, ?, ?)'); + $stmt->bind_param('ssssss', $userId, $username, $description, $action, $ipv4, $time); $stmt->execute(); $stmt->close(); } @@ -31,15 +31,15 @@ public static function addActivity(string $userId, string $username, string $des /** * Removes all activities for a specific user. * - * @param string $userId The user ID. + * @param string $userId the user ID */ public static function removeUserActivities(string $userId): void { $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $stmt = $conn->prepare("DELETE FROM framework_users_activities WHERE user_id = ?"); - $stmt->bind_param("s", $userId); + $stmt = $conn->prepare('DELETE FROM framework_users_activities WHERE user_id = ?'); + $stmt->bind_param('s', $userId); $stmt->execute(); $stmt->close(); } @@ -52,27 +52,28 @@ public static function removeAllActivities(): void $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $conn->query("TRUNCATE TABLE framework_users_activities"); + $conn->query('TRUNCATE TABLE framework_users_activities'); } /** * Gets activities for a specific user. * - * @param string $userId The user ID. + * @param string $userId the user ID * - * @return array The activities for the specified user. + * @return array the activities for the specified user */ public static function getActivities(string $userId): array { $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $stmt = $conn->prepare("SELECT * FROM framework_users_activities WHERE user_id = ?"); - $stmt->bind_param("s", $userId); + $stmt = $conn->prepare('SELECT * FROM framework_users_activities WHERE user_id = ?'); + $stmt->bind_param('s', $userId); $stmt->execute(); $result = $stmt->get_result(); $activities = $result->fetch_all(MYSQLI_ASSOC); $stmt->close(); + return $activities; } } diff --git a/app/Handlers/AnnouncementHandler.php b/app/Handlers/AnnouncementHandler.php index 7defb14..b54bc9d 100755 --- a/app/Handlers/AnnouncementHandler.php +++ b/app/Handlers/AnnouncementHandler.php @@ -2,22 +2,17 @@ namespace MythicalSystemsFramework\Handlers; -use MythicalSystemsFramework\Database\MySQL; -use Exception; -use MythicalSystemsFramework\Handlers\exception\AnnouncementNotFoundException; -use MythicalSystemsFramework\Handlers\interfaces\AnnouncementSocial; use MythicalSystemsFramework\Kernel\Logger; +use MythicalSystemsFramework\Database\MySQL; use MythicalSystemsFramework\Kernel\LoggerTypes; use MythicalSystemsFramework\Kernel\LoggerLevels; +use MythicalSystemsFramework\Handlers\interfaces\AnnouncementSocial; +use MythicalSystemsFramework\Handlers\exception\AnnouncementNotFoundException; class AnnouncementHandler implements AnnouncementSocial { /** * Does an announcement exist? - * - * @param int $id - * - * @return bool */ public static function exists(int $id): bool { @@ -25,15 +20,15 @@ public static function exists(int $id): bool $mysql = new MySQL(); $conn = $mysql->connectMYSQLI(); - $stmt = $conn->prepare("SELECT * FROM framework_announcements WHERE id = ?"); - $stmt->bind_param("i", $id); + $stmt = $conn->prepare('SELECT * FROM framework_announcements WHERE id = ?'); + $stmt->bind_param('i', $id); $stmt->execute(); $stmt->close(); - return $stmt->affected_rows > 0; - } catch (Exception $e) { - /** + return $stmt->affected_rows > 0; + } catch (\Exception $e) { + /* * Logger * * Logs something: LEVEL, TYPE, MESSAGE @@ -41,7 +36,8 @@ public static function exists(int $id): bool * LEVELS: INFO, WARNING, ERROR, CRITICAL, OTHER * TYPE: OTHER, CORE, DATABASE, PLUGIN, LOG, OTHER */ - Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, "An error occurred while checking if an announcement exists: " . $e->getMessage()); + Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, 'An error occurred while checking if an announcement exists: ' . $e->getMessage()); + return false; } } @@ -49,10 +45,7 @@ public static function exists(int $id): bool /** * Create a new announcement. * - * @param string $title - * @param string $text - * - * @return int The ID of the created announcement. + * @return int the ID of the created announcement */ public static function create(string $title, string $text): int { @@ -60,14 +53,15 @@ public static function create(string $title, string $text): int $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $stmt = $conn->prepare("INSERT INTO framework_announcements (title, text, date) VALUES (?, ?, NOW())"); - $stmt->bind_param("ss", $title, $text); + $stmt = $conn->prepare('INSERT INTO framework_announcements (title, text, date) VALUES (?, ?, NOW())'); + $stmt->bind_param('ss', $title, $text); $stmt->execute(); $announcementID = $stmt->insert_id; $stmt->close(); + return $announcementID; - } catch (Exception $e) { - /** + } catch (\Exception $e) { + /* * Logger * * Logs something: LEVEL, TYPE, MESSAGE @@ -75,25 +69,20 @@ public static function create(string $title, string $text): int * LEVELS: INFO, WARNING, ERROR, CRITICAL, OTHER * TYPE: OTHER, CORE, DATABASE, PLUGIN, LOG, OTHER */ - Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, "An error occurred while creating an announcement: " . $e->getMessage()); + Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, 'An error occurred while creating an announcement: ' . $e->getMessage()); + return -1; } } /** * Edit an existing announcement by ID. - * - * @param int $id - * @param string $title - * @param string $text - * - * @return void */ public static function edit(int $id, string $title, string $text): void { try { if (!self::exists($id)) { - /** + /* * Logger * * Logs something: LEVEL, TYPE, MESSAGE @@ -101,18 +90,18 @@ public static function edit(int $id, string $title, string $text): void * LEVELS: INFO, WARNING, ERROR, CRITICAL, OTHER * TYPE: OTHER, CORE, DATABASE, PLUGIN, LOG, OTHER */ - Logger::log(LoggerLevels::WARNING, LoggerTypes::OTHER, "An error occurred while editing an announcement: Announcement not found."); + Logger::log(LoggerLevels::WARNING, LoggerTypes::OTHER, 'An error occurred while editing an announcement: Announcement not found.'); throw new AnnouncementNotFoundException(); } $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $stmt = $conn->prepare("UPDATE framework_announcements SET title = ?, text = ? WHERE id = ?"); - $stmt->bind_param("ssi", $title, $text, $id); + $stmt = $conn->prepare('UPDATE framework_announcements SET title = ?, text = ? WHERE id = ?'); + $stmt->bind_param('ssi', $title, $text, $id); $stmt->execute(); $stmt->close(); - } catch (Exception $e) { - /** + } catch (\Exception $e) { + /* * Logger * * Logs something: LEVEL, TYPE, MESSAGE @@ -120,22 +109,19 @@ public static function edit(int $id, string $title, string $text): void * LEVELS: INFO, WARNING, ERROR, CRITICAL, OTHER * TYPE: OTHER, CORE, DATABASE, PLUGIN, LOG, OTHER */ - Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, "An error occurred while editing an announcement: " . $e->getMessage()); - throw new Exception("", $e->getCode(), $e); + Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, 'An error occurred while editing an announcement: ' . $e->getMessage()); + throw new \Exception('', $e->getCode(), $e); } } /** * Delete an announcement by ID. - * - * @param int $id - * @return void */ public static function delete(int $id): void { try { if (!self::exists($id)) { - /** + /* * Logger * * Logs something: LEVEL, TYPE, MESSAGE @@ -143,18 +129,18 @@ public static function delete(int $id): void * LEVELS: INFO, WARNING, ERROR, CRITICAL, OTHER * TYPE: OTHER, CORE, DATABASE, PLUGIN, LOG, OTHER */ - Logger::log(LoggerLevels::WARNING, LoggerTypes::OTHER, "An error occurred while deleting an announcement: Announcement not found."); + Logger::log(LoggerLevels::WARNING, LoggerTypes::OTHER, 'An error occurred while deleting an announcement: Announcement not found.'); throw new AnnouncementNotFoundException(); } $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $stmt = $conn->prepare("DELETE FROM framework_announcements WHERE id = ?"); - $stmt->bind_param("i", $id); + $stmt = $conn->prepare('DELETE FROM framework_announcements WHERE id = ?'); + $stmt->bind_param('i', $id); $stmt->execute(); $stmt->close(); - } catch (Exception $e) { - /** + } catch (\Exception $e) { + /* * Logger * * Logs something: LEVEL, TYPE, MESSAGE @@ -162,15 +148,13 @@ public static function delete(int $id): void * LEVELS: INFO, WARNING, ERROR, CRITICAL, OTHER * TYPE: OTHER, CORE, DATABASE, PLUGIN, LOG, OTHER */ - Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, "An error occurred while deleting an announcement: " . $e->getMessage()); - throw new Exception("", $e->getCode(), $e); + Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, 'An error occurred while deleting an announcement: ' . $e->getMessage()); + throw new \Exception('', $e->getCode(), $e); } } /** * Delete all framework_announcements. - * - * @return void */ public static function deleteAll(): void { @@ -178,9 +162,9 @@ public static function deleteAll(): void $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $conn->query("TRUNCATE TABLE framework_announcements"); - } catch (Exception $e) { - /** + $conn->query('TRUNCATE TABLE framework_announcements'); + } catch (\Exception $e) { + /* * Logger * * Logs something: LEVEL, TYPE, MESSAGE @@ -188,22 +172,19 @@ public static function deleteAll(): void * LEVELS: INFO, WARNING, ERROR, CRITICAL, OTHER * TYPE: OTHER, CORE, DATABASE, PLUGIN, LOG, OTHER */ - Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, "An error occurred while deleting all announcements: " . $e->getMessage()); - throw new Exception("", $e->getCode(), $e); + Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, 'An error occurred while deleting all announcements: ' . $e->getMessage()); + throw new \Exception('', $e->getCode(), $e); } } /** * Get a single announcement by ID. - * - * @param int $id - * @return array|null */ public static function getOne(int $id): ?array { try { if (!self::exists($id)) { - /** + /* * Logger * * Logs something: LEVEL, TYPE, MESSAGE @@ -211,21 +192,23 @@ public static function getOne(int $id): ?array * LEVELS: INFO, WARNING, ERROR, CRITICAL, OTHER * TYPE: OTHER, CORE, DATABASE, PLUGIN, LOG, OTHER */ - Logger::log(LoggerLevels::WARNING, LoggerTypes::OTHER, "An error occurred while getting an announcement: Announcement not found."); + Logger::log(LoggerLevels::WARNING, LoggerTypes::OTHER, 'An error occurred while getting an announcement: Announcement not found.'); + return []; } $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $stmt = $conn->prepare("SELECT * FROM framework_announcements WHERE id = ?"); - $stmt->bind_param("i", $id); + $stmt = $conn->prepare('SELECT * FROM framework_announcements WHERE id = ?'); + $stmt->bind_param('i', $id); $stmt->execute(); $result = $stmt->get_result(); $announcement = $result->fetch_assoc(); $stmt->close(); + return $announcement ? $announcement : null; - } catch (Exception $e) { - /** + } catch (\Exception $e) { + /* * Logger * * Logs something: LEVEL, TYPE, MESSAGE @@ -233,28 +216,27 @@ public static function getOne(int $id): ?array * LEVELS: INFO, WARNING, ERROR, CRITICAL, OTHER * TYPE: OTHER, CORE, DATABASE, PLUGIN, LOG, OTHER */ - Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, "An error occurred while getting an announcement: " . $e->getMessage()); + Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, 'An error occurred while getting an announcement: ' . $e->getMessage()); + return []; } } /** * Get all framework_announcements. - * - * @return array */ public static function getAll(): array { try { - $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $result = $conn->query("SELECT * FROM framework_announcements"); + $result = $conn->query('SELECT * FROM framework_announcements'); $framework_announcements = $result->fetch_all(MYSQLI_ASSOC); + return $framework_announcements; - } catch (Exception $e) { - /** + } catch (\Exception $e) { + /* * Logger * * Logs something: LEVEL, TYPE, MESSAGE @@ -262,15 +244,14 @@ public static function getAll(): array * LEVELS: INFO, WARNING, ERROR, CRITICAL, OTHER * TYPE: OTHER, CORE, DATABASE, PLUGIN, LOG, OTHER */ - Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, "An error occurred while getting all announcements: " . $e->getMessage()); + Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, 'An error occurred while getting all announcements: ' . $e->getMessage()); + return []; } } /** * Get all framework_announcements sorted by ID in descending order. - * - * @return array */ public static function getAllSortedById(): array { @@ -278,11 +259,12 @@ public static function getAllSortedById(): array $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $result = $conn->query("SELECT * FROM framework_announcements ORDER BY id DESC"); + $result = $conn->query('SELECT * FROM framework_announcements ORDER BY id DESC'); $framework_announcements = $result->fetch_all(MYSQLI_ASSOC); + return $framework_announcements; - } catch (Exception $e) { - /** + } catch (\Exception $e) { + /* * Logger * * Logs something: LEVEL, TYPE, MESSAGE @@ -290,15 +272,14 @@ public static function getAllSortedById(): array * LEVELS: INFO, WARNING, ERROR, CRITICAL, OTHER * TYPE: OTHER, CORE, DATABASE, PLUGIN, LOG, OTHER */ - Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, "An error occurred while getting all announcements sorted by ID: " . $e->getMessage()); + Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, 'An error occurred while getting all announcements sorted by ID: ' . $e->getMessage()); + return []; } } /** * Get all framework_announcements sorted by date in descending order. - * - * @return array */ public static function getAllSortedByDate(): array { @@ -306,11 +287,12 @@ public static function getAllSortedByDate(): array $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $result = $conn->query("SELECT * FROM framework_announcements ORDER BY date DESC"); + $result = $conn->query('SELECT * FROM framework_announcements ORDER BY date DESC'); $framework_announcements = $result->fetch_all(MYSQLI_ASSOC); + return $framework_announcements; - } catch (Exception $e) { - /** + } catch (\Exception $e) { + /* * Logger * * Logs something: LEVEL, TYPE, MESSAGE @@ -318,25 +300,22 @@ public static function getAllSortedByDate(): array * LEVELS: INFO, WARNING, ERROR, CRITICAL, OTHER * TYPE: OTHER, CORE, DATABASE, PLUGIN, LOG, OTHER */ - Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, "An error occurred while getting all announcements sorted by date: " . $e->getMessage()); + Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, 'An error occurred while getting all announcements sorted by date: ' . $e->getMessage()); + return []; } } + /** - * Summary of addSocialInteraction - * - * @param string $announcement_id - * @param string $user_uuid - * @param \MythicalSystemsFramework\Handlers\interfaces\AnnouncementSocial $type + * Summary of addSocialInteraction. * * @throws \Exception - * @return void */ public static function addSocialInteraction(string $announcement_id, string $user_uuid, AnnouncementSocial $type): void { try { if (!self::exists($announcement_id)) { - /** + /* * Logger * * Logs something: LEVEL, TYPE, MESSAGE @@ -344,17 +323,17 @@ public static function addSocialInteraction(string $announcement_id, string $use * LEVELS: INFO, WARNING, ERROR, CRITICAL, OTHER * TYPE: OTHER, CORE, DATABASE, PLUGIN, LOG, OTHER */ - Logger::log(LoggerLevels::WARNING, LoggerTypes::OTHER, "An error occurred while adding a social interaction to an announcement: Announcement not found."); + Logger::log(LoggerLevels::WARNING, LoggerTypes::OTHER, 'An error occurred while adding a social interaction to an announcement: Announcement not found.'); throw new AnnouncementNotFoundException(); } $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $stmt = $conn->prepare("INSERT INTO framework_announcements_social (announcement_id, user_uuid, type) VALUES (?, ?, ?)"); - $stmt->bind_param("iss", $announcement_id, $user_uuid, $type); + $stmt = $conn->prepare('INSERT INTO framework_announcements_social (announcement_id, user_uuid, type) VALUES (?, ?, ?)'); + $stmt->bind_param('iss', $announcement_id, $user_uuid, $type); $stmt->execute(); $stmt->close(); - } catch (Exception $e) { - /** + } catch (\Exception $e) { + /* * Logger * * Logs something: LEVEL, TYPE, MESSAGE @@ -362,26 +341,21 @@ public static function addSocialInteraction(string $announcement_id, string $use * LEVELS: INFO, WARNING, ERROR, CRITICAL, OTHER * TYPE: OTHER, CORE, DATABASE, PLUGIN, LOG, OTHER */ - Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, "An error occurred while adding a social interaction to an announcement: " . $e->getMessage()); - throw new Exception('' . $e->getMessage()); + Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, 'An error occurred while adding a social interaction to an announcement: ' . $e->getMessage()); + throw new \Exception('' . $e->getMessage()); } } + /** - * Summary of removeSocialInteraction - * - * @param string $announcement_id - * @param string $user_uuid - * @param \MythicalSystemsFramework\Handlers\interfaces\AnnouncementSocial $type + * Summary of removeSocialInteraction. * * @throws \Exception - * @return void */ public static function removeSocialInteraction(string $announcement_id, string $user_uuid, AnnouncementSocial $type): void { - try { if (!self::exists($announcement_id)) { - /** + /* * Logger * * Logs something: LEVEL, TYPE, MESSAGE @@ -389,17 +363,17 @@ public static function removeSocialInteraction(string $announcement_id, string $ * LEVELS: INFO, WARNING, ERROR, CRITICAL, OTHER * TYPE: OTHER, CORE, DATABASE, PLUGIN, LOG, OTHER */ - Logger::log(LoggerLevels::WARNING, LoggerTypes::OTHER, "An error occurred while removing a social interaction from an announcement: Announcement not found."); + Logger::log(LoggerLevels::WARNING, LoggerTypes::OTHER, 'An error occurred while removing a social interaction from an announcement: Announcement not found.'); throw new AnnouncementNotFoundException(); } $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $stmt = $conn->prepare("DELETE FROM framework_announcements_social WHERE announcement_id = ? AND user_uuid = ? AND type = ?"); - $stmt->bind_param("iss", $announcement_id, $user_uuid, $type); + $stmt = $conn->prepare('DELETE FROM framework_announcements_social WHERE announcement_id = ? AND user_uuid = ? AND type = ?'); + $stmt->bind_param('iss', $announcement_id, $user_uuid, $type); $stmt->execute(); $stmt->close(); - } catch (Exception $e) { - /** + } catch (\Exception $e) { + /* * Logger * * Logs something: LEVEL, TYPE, MESSAGE @@ -407,24 +381,19 @@ public static function removeSocialInteraction(string $announcement_id, string $ * LEVELS: INFO, WARNING, ERROR, CRITICAL, OTHER * TYPE: OTHER, CORE, DATABASE, PLUGIN, LOG, OTHER */ - Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, "An error occurred while removing a social interaction from an announcement: " . $e->getMessage()); - throw new Exception('' . $e->getMessage()); + Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, 'An error occurred while removing a social interaction from an announcement: ' . $e->getMessage()); + throw new \Exception('' . $e->getMessage()); } } + /** - * Summary of getSocialInteraction - * - * @param string $announcement_id - * @param string $user_uuid - * @param string $type - * - * @return bool + * Summary of getSocialInteraction. */ public static function getSocialInteraction(string $announcement_id, string $user_uuid, string $type): bool { try { if (!self::exists($announcement_id)) { - /** + /* * Logger * * Logs something: LEVEL, TYPE, MESSAGE @@ -432,7 +401,8 @@ public static function getSocialInteraction(string $announcement_id, string $use * LEVELS: INFO, WARNING, ERROR, CRITICAL, OTHER * TYPE: OTHER, CORE, DATABASE, PLUGIN, LOG, OTHER */ - Logger::log(LoggerLevels::WARNING, LoggerTypes::OTHER, "An error occurred while getting a social interaction from an announcement: Announcement not found."); + Logger::log(LoggerLevels::WARNING, LoggerTypes::OTHER, 'An error occurred while getting a social interaction from an announcement: Announcement not found.'); + return false; } $mysqli = new MySQL(); @@ -448,9 +418,8 @@ public static function getSocialInteraction(string $announcement_id, string $use } else { return false; } - - } catch (Exception $e) { - /** + } catch (\Exception $e) { + /* * Logger * * Logs something: LEVEL, TYPE, MESSAGE @@ -458,23 +427,20 @@ public static function getSocialInteraction(string $announcement_id, string $use * LEVELS: INFO, WARNING, ERROR, CRITICAL, OTHER * TYPE: OTHER, CORE, DATABASE, PLUGIN, LOG, OTHER */ - Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, "An error occurred while getting a social interaction from an announcement: " . $e->getMessage()); + Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, 'An error occurred while getting a social interaction from an announcement: ' . $e->getMessage()); + return false; } } + /** - * Summary of getTotalSocialInteractions - * - * @param string $announcement_id - * @param string $type - * - * @return int + * Summary of getTotalSocialInteractions. */ public static function getTotalSocialInteractions(string $announcement_id, string $type): int { try { if (!self::exists($announcement_id)) { - /** + /* * Logger * * Logs something: LEVEL, TYPE, MESSAGE @@ -482,7 +448,8 @@ public static function getTotalSocialInteractions(string $announcement_id, strin * LEVELS: INFO, WARNING, ERROR, CRITICAL, OTHER * TYPE: OTHER, CORE, DATABASE, PLUGIN, LOG, OTHER */ - Logger::log(LoggerLevels::WARNING, LoggerTypes::OTHER, "An error occurred while getting the total social interactions from an announcement: Announcement not found."); + Logger::log(LoggerLevels::WARNING, LoggerTypes::OTHER, 'An error occurred while getting the total social interactions from an announcement: Announcement not found.'); + return 0; } $mysqli = new MySQL(); @@ -497,8 +464,8 @@ public static function getTotalSocialInteractions(string $announcement_id, strin } else { return 0; } - } catch (Exception $e) { - /** + } catch (\Exception $e) { + /* * Logger * * Logs something: LEVEL, TYPE, MESSAGE @@ -506,9 +473,9 @@ public static function getTotalSocialInteractions(string $announcement_id, strin * LEVELS: INFO, WARNING, ERROR, CRITICAL, OTHER * TYPE: OTHER, CORE, DATABASE, PLUGIN, LOG, OTHER */ - Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, "An error occurred while getting the total social interactions from an announcement: " . $e->getMessage()); + Logger::log(LoggerLevels::ERROR, LoggerTypes::OTHER, 'An error occurred while getting the total social interactions from an announcement: ' . $e->getMessage()); + return 0; } } - } diff --git a/app/Handlers/CacheHandler.php b/app/Handlers/CacheHandler.php index 40e185c..00fa469 100755 --- a/app/Handlers/CacheHandler.php +++ b/app/Handlers/CacheHandler.php @@ -7,25 +7,23 @@ class CacheHandler { public static $cache_file = __DIR__ . '/../../caches/cache.json'; + /** - * Create the cache file - * - * @return void + * Create the cache file. */ public static function createFile(): void { if (!file_exists(self::$cache_file)) { - file_put_contents(self::$cache_file, "{}"); + file_put_contents(self::$cache_file, '{}'); } } /** * Set a value in the cache with a specified expiration time in seconds. * - * @param string $key The key to store the value under. - * @param mixed $value The value to store in the cache. - * @param int $expirySeconds The number of seconds after which the cache entry will expire. - * @return void + * @param string $key the key to store the value under + * @param mixed $value the value to store in the cache + * @param int $expirySeconds the number of seconds after which the cache entry will expire */ public static function set(string $key, mixed $value, int $expirySeconds): void { @@ -38,24 +36,24 @@ public static function set(string $key, mixed $value, int $expirySeconds): void /** * Get a value from the cache if it exists and is not expired. * - * @param string $key The key of the value to retrieve. - * @return mixed The cached value if it exists and is not expired, or null otherwise. + * @param string $key the key of the value to retrieve + * + * @return mixed the cached value if it exists and is not expired, or null otherwise */ public static function get(string $key): mixed { self::createFile(); $core = new MythicalCoreCache(self::$cache_file); + return $core->get($key); } /** * Update an existing cache entry with a new value and expiration time. * - * @param string $key The key of the cache entry to update. - * @param mixed $value The new value to set for the cache entry. - * @param int $expiryTimestamp The new expiration timestamp for the cache entry. - * - * @return void + * @param string $key the key of the cache entry to update + * @param mixed $value the new value to set for the cache entry + * @param int $expiryTimestamp the new expiration timestamp for the cache entry */ public function update(string $key, mixed $value, int $expiryTimestamp): void { @@ -63,12 +61,11 @@ public function update(string $key, mixed $value, int $expiryTimestamp): void $core = new MythicalCoreCache(self::$cache_file); $core->update($key, $value, $expiryTimestamp); } + /** * Delete a cache entry by key. * - * @param string $key The key of the cache entry to delete. - * - * @return void + * @param string $key the key of the cache entry to delete */ public function delete($key): void { @@ -79,8 +76,6 @@ public function delete($key): void /** * Purge the entire cache, removing all entries. - * - * @return void */ public static function purge(): void { @@ -91,8 +86,6 @@ public static function purge(): void /** * Purge the entire cache, removing all entries. - * - * @return void */ public static function process(): void { diff --git a/app/Handlers/NotificationHandler.php b/app/Handlers/NotificationHandler.php index c6eb354..655e488 100755 --- a/app/Handlers/NotificationHandler.php +++ b/app/Handlers/NotificationHandler.php @@ -2,7 +2,6 @@ namespace MythicalSystemsFramework\Handlers; -use Exception; use MythicalSystemsFramework\Database\MySQL; class NotificationHandler @@ -10,94 +9,89 @@ class NotificationHandler /** * Create a new notification. * - * @param string $user_id The user id. - * @param string $name The notification name. - * @param string $description The notification description. + * @param string $user_id the user id + * @param string $name the notification name + * @param string $description the notification description * - * @return int The id of the created notification. + * @return int the id of the created notification */ public static function create(string $user_id, string $name, string $description): int { try { $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $stmt = $conn->prepare("INSERT INTO framework_users_notifications (user_id, name, description, date) VALUES (?, ?, ?, NOW())"); - $stmt->bind_param("sss", $user_id, $name, $description); + $stmt = $conn->prepare('INSERT INTO framework_users_notifications (user_id, name, description, date) VALUES (?, ?, ?, NOW())'); + $stmt->bind_param('sss', $user_id, $name, $description); $stmt->execute(); $notificationID = $stmt->insert_id; $stmt->close(); + return $notificationID; - } catch (Exception $e) { - throw new Exception("" . $e->getMessage()); + } catch (\Exception $e) { + throw new \Exception('' . $e->getMessage()); } } /** * Edit an existing notification by ID. * - * @param int $id The id of the notification to edit. - * @param string $name The new notification name. - * @param string $description The new notification description. - * - * @return void + * @param int $id the id of the notification to edit + * @param string $name the new notification name + * @param string $description the new notification description */ public static function edit(int $id, string $name, string $description): void { try { $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $stmt = $conn->prepare("UPDATE framework_users_notifications SET name = ?, description = ? WHERE id = ?"); - $stmt->bind_param("ssi", $name, $description, $id); + $stmt = $conn->prepare('UPDATE framework_users_notifications SET name = ?, description = ? WHERE id = ?'); + $stmt->bind_param('ssi', $name, $description, $id); $stmt->execute(); $stmt->close(); - } catch (Exception $e) { - throw new Exception("" . $e->getMessage()); + } catch (\Exception $e) { + throw new \Exception('' . $e->getMessage()); } } /** * Delete a notification by ID. * - * @param int $id The id of the notification to delete. - * - * @return void + * @param int $id the id of the notification to delete */ public static function delete(int $id): void { try { $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $stmt = $conn->prepare("DELETE FROM framework_users_notifications WHERE id = ?"); - $stmt->bind_param("i", $id); + $stmt = $conn->prepare('DELETE FROM framework_users_notifications WHERE id = ?'); + $stmt->bind_param('i', $id); $stmt->execute(); $stmt->close(); - } catch (Exception $e) { - throw new Exception("" . $e->getMessage()); + } catch (\Exception $e) { + throw new \Exception('' . $e->getMessage()); } } /** * Delete all framework_users_notifications. - * - * @return void */ public static function deleteAll(): void { try { $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $conn->query("TRUNCATE TABLE framework_users_notifications"); - } catch (Exception $e) { - throw new Exception("" . $e->getMessage()); + $conn->query('TRUNCATE TABLE framework_users_notifications'); + } catch (\Exception $e) { + throw new \Exception('' . $e->getMessage()); } } /** * Get a single notification by ID. * - * @param int $id The id of the notification to retrieve. + * @param int $id the id of the notification to retrieve * - * @return array|null The notification data or null if not found. + * @return array|null the notification data or null if not found */ public static function getOne(int $id): ?array { @@ -107,14 +101,15 @@ public static function getOne(int $id): ?array } $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $stmt = $conn->prepare("SELECT * FROM framework_users_notifications WHERE id = ?"); - $stmt->bind_param("i", $id); + $stmt = $conn->prepare('SELECT * FROM framework_users_notifications WHERE id = ?'); + $stmt->bind_param('i', $id); $stmt->execute(); $result = $stmt->get_result(); $notification = $result->fetch_assoc(); $stmt->close(); + return $notification; - } catch (Exception $e) { + } catch (\Exception $e) { return []; } } @@ -122,20 +117,21 @@ public static function getOne(int $id): ?array /** * Get all framework_users_notifications. * - * @return array All framework_users_notifications. + * @return array all framework_users_notifications */ public static function getAll(): array { try { $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $result = $conn->query("SELECT * FROM framework_users_notifications"); + $result = $conn->query('SELECT * FROM framework_users_notifications'); $framework_users_notifications = []; while ($notification = $result->fetch_assoc()) { $framework_users_notifications[] = $notification; } + return $framework_users_notifications; - } catch (Exception $e) { + } catch (\Exception $e) { return []; } } @@ -143,20 +139,21 @@ public static function getAll(): array /** * Get all framework_users_notifications sorted by ID in descending order. * - * @return array Sorted framework_users_notifications. + * @return array sorted framework_users_notifications */ public static function getAllSortedById(): array { try { $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $result = $conn->query("SELECT * FROM framework_users_notifications ORDER BY id DESC"); + $result = $conn->query('SELECT * FROM framework_users_notifications ORDER BY id DESC'); $framework_users_notifications = []; while ($notification = $result->fetch_assoc()) { $framework_users_notifications[] = $notification; } + return $framework_users_notifications; - } catch (Exception $e) { + } catch (\Exception $e) { return []; } } @@ -164,20 +161,21 @@ public static function getAllSortedById(): array /** * Get all framework_users_notifications sorted by date in descending order. * - * @return array Sorted framework_users_notifications. + * @return array sorted framework_users_notifications */ public static function getAllSortedByDate(): array { try { $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $result = $conn->query("SELECT * FROM framework_users_notifications ORDER BY date DESC"); + $result = $conn->query('SELECT * FROM framework_users_notifications ORDER BY date DESC'); $framework_users_notifications = []; while ($notification = $result->fetch_assoc()) { $framework_users_notifications[] = $notification; } + return $framework_users_notifications; - } catch (Exception $e) { + } catch (\Exception $e) { return []; } } @@ -185,17 +183,17 @@ public static function getAllSortedByDate(): array /** * Get framework_users_notifications filtered by user ID. * - * @param string $user_id The user id to filter by. + * @param string $user_id the user id to filter by * - * @return array Filtered framework_users_notifications. + * @return array filtered framework_users_notifications */ public static function getByUserId(string $user_id): array { try { $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $stmt = $conn->prepare("SELECT * FROM framework_users_notifications WHERE user_id = ?"); - $stmt->bind_param("s", $user_id); + $stmt = $conn->prepare('SELECT * FROM framework_users_notifications WHERE user_id = ?'); + $stmt->bind_param('s', $user_id); $stmt->execute(); $result = $stmt->get_result(); $framework_users_notifications = []; @@ -203,30 +201,33 @@ public static function getByUserId(string $user_id): array $framework_users_notifications[] = $notification; } $stmt->close(); + return $framework_users_notifications; - } catch (Exception $e) { + } catch (\Exception $e) { return []; } } + /** * Does a notification exist in the database? * - * @param int $id The id of the notification to check. + * @param int $id the id of the notification to check * - * @return bool True if the notification exists, false if not. + * @return bool true if the notification exists, false if not */ public static function exists(string $id): bool { try { $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $stmt = $conn->prepare("SELECT * FROM framework_users_notifications WHERE id = ?"); - $stmt->bind_param("i", $id); + $stmt = $conn->prepare('SELECT * FROM framework_users_notifications WHERE id = ?'); + $stmt->bind_param('i', $id); $stmt->execute(); $result = $stmt->get_result(); $stmt->close(); + return $result->num_rows > 0; - } catch (Exception $e) { + } catch (\Exception $e) { return false; } } @@ -234,48 +235,47 @@ public static function exists(string $id): bool /** * Mark a notification as read. * - * @param string $notification_id The id of the notification to mark as read. - * @param string $user_uuid The user uuid. + * @param string $notification_id the id of the notification to mark as read + * @param string $user_uuid the user uuid * - * @return void - * @throws Exception + * @throws \Exception */ public static function markAsRead(string $notification_id, string $user_uuid): void { try { $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $stmt = $conn->prepare("INSERT INTO framework_users_notifications_read (notification_id, user_uuid, date) VALUES (?, ?, NOW())"); - $stmt->bind_param("ss", $notification_id, $user_uuid); + $stmt = $conn->prepare('INSERT INTO framework_users_notifications_read (notification_id, user_uuid, date) VALUES (?, ?, NOW())'); + $stmt->bind_param('ss', $notification_id, $user_uuid); $stmt->execute(); $stmt->close(); - } catch (Exception $e) { - throw new Exception("" . $e->getMessage()); + } catch (\Exception $e) { + throw new \Exception('' . $e->getMessage()); } } + /** * Check if a notification was already read! * * @param string $notification_id The id of the notification * @param string $user_uuid The uuid of the user * - * @throws Exception - * @return bool + * @throws \Exception */ public static function hasAlreadyRead(string $notification_id, string $user_uuid): bool { try { $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $stmt = $conn->prepare("SELECT * FROM framework_users_notifications_read WHERE notification_id = ? AND user_uuid = ?"); - $stmt->bind_param("ss", $notification_id, $user_uuid); + $stmt = $conn->prepare('SELECT * FROM framework_users_notifications_read WHERE notification_id = ? AND user_uuid = ?'); + $stmt->bind_param('ss', $notification_id, $user_uuid); $stmt->execute(); $result = $stmt->get_result(); $stmt->close(); + return $result->num_rows > 0; - } catch (Exception $e) { - throw new Exception("" . $e->getMessage()); + } catch (\Exception $e) { + throw new \Exception('' . $e->getMessage()); } } - } diff --git a/app/Handlers/exception/AnnouncementNotFoundException.php b/app/Handlers/exception/AnnouncementNotFoundException.php index acb8a33..8bbf1cf 100755 --- a/app/Handlers/exception/AnnouncementNotFoundException.php +++ b/app/Handlers/exception/AnnouncementNotFoundException.php @@ -4,7 +4,7 @@ class AnnouncementNotFoundException extends \Exception { - public function __construct($message = "Announcement not found.", $code = 0, \Throwable $previous = null) + public function __construct($message = 'Announcement not found.', $code = 0, ?\Throwable $previous = null) { parent::__construct($message, $code, $previous); } diff --git a/app/Handlers/exception/NotificationNotFoundException.php b/app/Handlers/exception/NotificationNotFoundException.php index b514849..004fe36 100755 --- a/app/Handlers/exception/NotificationNotFoundException.php +++ b/app/Handlers/exception/NotificationNotFoundException.php @@ -4,7 +4,7 @@ class NotificationNotFoundException extends \Exception { - public function __construct($message = "Notification not found.", $code = 0, \Exception $previous = null) + public function __construct($message = 'Notification not found.', $code = 0, ?\Exception $previous = null) { parent::__construct($message, $code, $previous); } diff --git a/app/Handlers/interfaces/AnnouncementSocial.php b/app/Handlers/interfaces/AnnouncementSocial.php index bc8a92b..5d13736 100755 --- a/app/Handlers/interfaces/AnnouncementSocial.php +++ b/app/Handlers/interfaces/AnnouncementSocial.php @@ -7,4 +7,4 @@ interface AnnouncementSocial public static const Read = "read"; public static const Like = "like"; public static const Dislike = "dislike"; -} \ No newline at end of file +} diff --git a/app/Kernel/Debugger.php b/app/Kernel/Debugger.php index d43e239..0bb493b 100755 --- a/app/Kernel/Debugger.php +++ b/app/Kernel/Debugger.php @@ -2,29 +2,24 @@ namespace MythicalSystemsFramework\Kernel; -use Exception; - class Debugger { /** - * Display the information + * Display the information. * * @param mixed $input The input to display the info about! * @param bool $collapse This is always false by default - * - * @return void */ public static function display_info($input, $collapse = false): void { - try { $recursive = function ($data, $level = 0) use (&$recursive, $collapse) { global $argv; $isTerminal = isset($argv); - if (!$isTerminal && $level == 0 && !defined("DUMP_DEBUG_SCRIPT")) { - define("DUMP_DEBUG_SCRIPT", true); + if (!$isTerminal && $level == 0 && !defined('DUMP_DEBUG_SCRIPT')) { + define('DUMP_DEBUG_SCRIPT', true); echo '' . "\n"; } - $type = !is_string($data) && is_callable($data) ? "Callable" : ucfirst(gettype($data)); + $type = !is_string($data) && is_callable($data) ? 'Callable' : ucfirst(gettype($data)); $type_data = null; $type_color = null; $type_length = null; switch ($type) { - case "String": - $type_color = "green"; + case 'String': + $type_color = 'green'; $type_length = strlen($data); - $type_data = "\"" . htmlentities($data) . "\""; + $type_data = '"' . htmlentities($data) . '"'; break; - case "Double": - case "Float": - $type = "Float"; - $type_color = "#0099c5"; + case 'Double': + case 'Float': + $type = 'Float'; + $type_color = '#0099c5'; $type_length = strlen($data); $type_data = htmlentities($data); break; - case "Integer": - $type_color = "red"; + case 'Integer': + $type_color = 'red'; $type_length = strlen($data); $type_data = htmlentities($data); break; - case "Boolean": - $type_color = "#92008d"; + case 'Boolean': + $type_color = '#92008d'; $type_length = strlen($data); - $type_data = $data ? "TRUE" : "FALSE"; + $type_data = $data ? 'TRUE' : 'FALSE'; break; - case "NULL": + case 'NULL': $type_length = 0; break; - case "Array": + case 'Array': $type_length = count($data); } - if (in_array($type, array("Object", "Array"))) { + if (in_array($type, ['Object', 'Array'])) { $notEmpty = false; foreach ($data as $key => $value) { @@ -81,69 +76,69 @@ public static function display_info($input, $collapse = false): void $notEmpty = true; if ($isTerminal) { - echo $type . ($type_length !== null ? "(" . $type_length . ")" : "") . "\n"; + echo $type . ($type_length !== null ? '(' . $type_length . ')' : '') . "\n"; } else { - $id = substr(md5(rand() . ":" . $key . ":" . $level), 0, 8); + $id = substr(md5(mt_rand() . ':' . $key . ':' . $level), 0, 8); echo ""; - echo "" . $type . ($type_length !== null ? "(" . $type_length . ")" : "") . ""; - echo ""; - echo " ⤵"; - echo "
"; - echo "
"; + echo "" . $type . ($type_length !== null ? '(' . $type_length . ')' : '') . ''; + echo ''; + echo ' ⤵'; + echo '
'; + echo '
'; } - for ($i = 0; $i <= $level; $i++) { - echo $isTerminal ? "| " : "|        "; + for ($i = 0; $i <= $level; ++$i) { + echo $isTerminal ? '| ' : "|        "; } - echo $isTerminal ? "\n" : "
"; + echo $isTerminal ? "\n" : '
'; } - for ($i = 0; $i <= $level; $i++) { - echo $isTerminal ? "| " : "|        "; + for ($i = 0; $i <= $level; ++$i) { + echo $isTerminal ? '| ' : "|        "; } - echo $isTerminal ? "[" . $key . "] => " : "[" . $key . "] => "; + echo $isTerminal ? '[' . $key . '] => ' : "[" . $key . '] => '; call_user_func($recursive, $value, $level + 1); } if ($notEmpty) { - for ($i = 0; $i <= $level; $i++) { - echo $isTerminal ? "| " : "|        "; + for ($i = 0; $i <= $level; ++$i) { + echo $isTerminal ? '| ' : "|        "; } if (!$isTerminal) { - echo "
"; + echo '
'; } } else { echo $isTerminal ? - $type . ($type_length !== null ? "(" . $type_length . ")" : "") . " " : - "" . $type . ($type_length !== null ? "(" . $type_length . ")" : "") . "  "; + $type . ($type_length !== null ? '(' . $type_length . ')' : '') . ' ' : + "" . $type . ($type_length !== null ? '(' . $type_length . ')' : '') . '  '; } } else { echo $isTerminal ? - $type . ($type_length !== null ? "(" . $type_length . ")" : "") . " " : - "" . $type . ($type_length !== null ? "(" . $type_length . ")" : "") . "  "; + $type . ($type_length !== null ? '(' . $type_length . ')' : '') . ' ' : + "" . $type . ($type_length !== null ? '(' . $type_length . ')' : '') . '  '; if ($type_data != null) { - echo $isTerminal ? $type_data : "" . $type_data . ""; + echo $isTerminal ? $type_data : "" . $type_data . ''; } } - echo $isTerminal ? "\n" : "
"; + echo $isTerminal ? "\n" : '
'; }; call_user_func($recursive, $input); - die(); - } catch (Exception $e) { - die($e->getMessage()); + exit; + } catch (\Exception $e) { + exit($e->getMessage()); } } /** - * Throw an error + * Throw an error. * * @param mixed $renderer The twig renderer * @param string $error_text The error text @@ -166,12 +161,12 @@ public static function throw_error($renderer, $error_text, $error_full_message, global $renderer; http_response_code(500); - die($renderer->render('/errors/debug.twig')); + exit($renderer->render('/errors/debug.twig')); }); - die($router->route()); - } catch (Exception $e) { - die($e->getMessage()); + exit($router->route()); + } catch (\Exception $e) { + exit($e->getMessage()); } } } diff --git a/app/Kernel/Encryption.php b/app/Kernel/Encryption.php index 5fe8f34..ad4a9c7 100755 --- a/app/Kernel/Encryption.php +++ b/app/Kernel/Encryption.php @@ -2,32 +2,24 @@ namespace MythicalSystemsFramework\Kernel; -use MythicalSystems\Utils\EncryptionHandler as core_encryption; use MythicalSystemsFramework\Managers\ConfigManager as cfg; +use MythicalSystems\Utils\EncryptionHandler as core_encryption; class Encryption { /** - * Encrypt the data - * - * @param string $data - * - * @return string + * Encrypt the data. */ public static function encrypt(string $data): string { - return core_encryption::encrypt($data, cfg::get("encryption", "key")); + return core_encryption::encrypt($data, cfg::get('encryption', 'key')); } /** - * Decrypt the data - * - * @param string $data - * - * @return string + * Decrypt the data. */ public static function decrypt(string $data): string { - return core_encryption::decrypt($data, cfg::get("encryption", "key")); + return core_encryption::decrypt($data, cfg::get('encryption', 'key')); } } diff --git a/app/Kernel/Logger.php b/app/Kernel/Logger.php index a363fed..be44fdf 100755 --- a/app/Kernel/Logger.php +++ b/app/Kernel/Logger.php @@ -2,15 +2,12 @@ namespace MythicalSystemsFramework\Kernel; -use Exception; use MythicalSystemsFramework\Database\MySQL; -use MythicalSystemsFramework\Kernel\LoggerTypes; -use MythicalSystemsFramework\Kernel\LoggerLevels; class Logger { /** - * Log something inside the kernel framework_logs + * Log something inside the kernel framework_logs. * * @param LoggerTypes|string $level (INFO, WARNING, ERROR, CRITICAL, OTHER) * @param LoggerLevels|string $type (CORE, DATABASE, PLUGIN, LOG, OTHER, LANGUAGE) @@ -23,13 +20,13 @@ public static function log(LoggerTypes|string $level, LoggerLevels|string $type, $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); if (empty($level) || empty($type)) { - throw new Exception("Both log level and type must be provided"); + throw new \Exception('Both log level and type must be provided'); } - $output = "[" . date("Y-m-d H:i:s") . "] (" . $type . '/' . $level . ") " . $message . ""; + $output = '[' . date('Y-m-d H:i:s') . '] (' . $type . '/' . $level . ') ' . $message . ''; - $stmt = $conn->prepare("INSERT INTO framework_logs (l_type, levels, message, formatted) VALUES (?, ?, ?, ?)"); - $stmt->bind_param("ssss", $type, $level, $message, $output); + $stmt = $conn->prepare('INSERT INTO framework_logs (l_type, levels, message, formatted) VALUES (?, ?, ?, ?)'); + $stmt->bind_param('ssss', $type, $level, $message, $output); $stmt->execute(); $logId = $stmt->insert_id; $stmt->close(); @@ -39,76 +36,67 @@ public static function log(LoggerTypes|string $level, LoggerLevels|string $type, /** * Delete a log by ID. - * - * @param int $id - * @return void */ public static function delete(int $id): void { $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $stmt = $conn->prepare("DELETE FROM framework_logs WHERE id = ?"); - $stmt->bind_param("i", $id); + $stmt = $conn->prepare('DELETE FROM framework_logs WHERE id = ?'); + $stmt->bind_param('i', $id); $stmt->execute(); $stmt->close(); } /** * Delete all framework_logs. - * - * @return void */ public static function deleteAll(): void { $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $conn->query("TRUNCATE TABLE framework_logs"); + $conn->query('TRUNCATE TABLE framework_logs'); } /** * Get a single log by ID. - * - * @param int $id - * @return array|null */ public static function getOne(int $id): ?array { $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $stmt = $conn->prepare("SELECT * FROM framework_logs WHERE id = ?"); - $stmt->bind_param("i", $id); + $stmt = $conn->prepare('SELECT * FROM framework_logs WHERE id = ?'); + $stmt->bind_param('i', $id); $stmt->execute(); $result = $stmt->get_result(); $log = $result->fetch_assoc(); $stmt->close(); + return $log ? $log : null; } /** * Get all framework_logs. - * - * @return array */ public static function getAll(): array { $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $result = $conn->query("SELECT * FROM framework_logs"); + $result = $conn->query('SELECT * FROM framework_logs'); $framework_logs = $result->fetch_all(MYSQLI_ASSOC); + return $framework_logs; } /** * Get all framework_logs sorted by ID in descending order. - * - * @return array */ public static function getAllSortedById(): array { $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $result = $conn->query("SELECT * FROM framework_logs ORDER BY id DESC"); + $result = $conn->query('SELECT * FROM framework_logs ORDER BY id DESC'); $framework_logs = $result->fetch_all(MYSQLI_ASSOC); + return $framework_logs; } @@ -121,17 +109,18 @@ public static function getAllSortedById(): array * * @return array|null Returns the logs in an array */ - public static function getAllSortedByDate(LoggerTypes|string $level, LoggerLevels|string $type, int $limit = 15): array|null + public static function getAllSortedByDate(LoggerTypes|string $level, LoggerLevels|string $type, int $limit = 15): ?array { $mysqli = new MySQL(); $conn = $mysqli->connectMYSQLI(); - $query = "SELECT * FROM framework_logs WHERE levels = ? AND l_type = ? ORDER BY date DESC LIMIT ?"; + $query = 'SELECT * FROM framework_logs WHERE levels = ? AND l_type = ? ORDER BY date DESC LIMIT ?'; $stmt = $conn->prepare($query); - $stmt->bind_param("ssi", $level, $type, $limit); + $stmt->bind_param('ssi', $level, $type, $limit); $stmt->execute(); $result = $stmt->get_result(); $framework_logs = $result->fetch_all(MYSQLI_ASSOC); $stmt->close(); + return $framework_logs; } } diff --git a/app/Kernel/LoggerTypes.php b/app/Kernel/LoggerTypes.php index fbd654f..be5b68b 100755 --- a/app/Kernel/LoggerTypes.php +++ b/app/Kernel/LoggerTypes.php @@ -9,7 +9,7 @@ interface LoggerTypes public const DATABASE = 'DATABASE'; public const PLUGIN = 'PLUGIN'; public const LOG = 'LOG'; - public const LANGUAGE = "LANGUAGE"; + public const LANGUAGE = 'LANGUAGE'; // Other public const OTHER = 'OTHER'; } diff --git a/app/Managers/ConfigManager.php b/app/Managers/ConfigManager.php index 7114cb3..3500cc7 100755 --- a/app/Managers/ConfigManager.php +++ b/app/Managers/ConfigManager.php @@ -2,12 +2,12 @@ namespace MythicalSystemsFramework\Managers; -use Exception; use MythicalSystems\Helpers\ConfigHelper; class ConfigManager { - private static string $configpath = __DIR__ . "/../../settings.json"; + private static string $configpath = __DIR__ . '/../../settings.json'; + /** * DEPRECATED: Use Settings class instead!! * DEPRECATED: This class is used for the settings.json file! @@ -15,24 +15,22 @@ class ConfigManager * Get value form the config! * * @param string $category The category of the value you want to take from the config - * @param string $value The value you want to take from the config file! - * - * @return string|null */ - public static function get(string $category, string $key): string|null + public static function get(string $category, string $key): ?string { try { if (!file_exists(self::$configpath)) { - die("Config file not found!"); + exit('Config file not found!'); } if (!is_writable(self::$configpath)) { - die("We have no access to the config file!"); + exit('We have no access to the config file!'); } else { $config = new ConfigHelper(self::$configpath); } - } catch (Exception $e) { - die("Failed to init the config class! \n" . $e->__toString()); + } catch (\Exception $e) { + exit("Failed to init the config class! \n" . $e->__toString()); } + return $config->get($category, $key); } @@ -51,16 +49,17 @@ public static function set(string $category, string $key, string $value): bool { try { if (!file_exists(self::$configpath)) { - die("Config file not found!"); + exit('Config file not found!'); } if (!is_writable(self::$configpath)) { - die("We have no access to the config file!"); + exit('We have no access to the config file!'); } else { $config = new ConfigHelper(self::$configpath); } - } catch (Exception $e) { - die("Failed to init the config class! \n" . $e->__toString()); + } catch (\Exception $e) { + exit("Failed to init the config class! \n" . $e->__toString()); } + return $config->set($category, $key, $value); } @@ -73,23 +72,22 @@ public static function set(string $category, string $key, string $value): bool * @param string $category The category of the value you want to add in the config * @param string $key The key of the value you want to add in the config file! * @param string $value The value you want to add in the config file! - * - * @return bool */ public static function add(string $category, string $key, string $value): bool { try { if (!file_exists(self::$configpath)) { - die("Config file not found!"); + exit('Config file not found!'); } if (!is_writable(self::$configpath)) { - die("We have no access to the config file!"); + exit('We have no access to the config file!'); } else { $config = new ConfigHelper(self::$configpath); } - } catch (Exception $e) { - die("Failed to init the config class! \n" . $e->__toString()); + } catch (\Exception $e) { + exit("Failed to init the config class! \n" . $e->__toString()); } + return $config->add($category, $key, $value); } @@ -101,23 +99,22 @@ public static function add(string $category, string $key, string $value): bool * * @param string $category The category of the value you want to remove from the config * @param string $key The key of the value you want to remove from the config file! - * - * @return bool */ public static function remove(string $category, string $key): bool { try { if (!file_exists(self::$configpath)) { - die("Config file not found!"); + exit('Config file not found!'); } if (!is_writable(self::$configpath)) { - die("We have no access to the config file!"); + exit('We have no access to the config file!'); } else { $config = new ConfigHelper(self::$configpath); } - } catch (Exception $e) { - die("Failed to init the config class! \n" . $e->__toString()); + } catch (\Exception $e) { + exit("Failed to init the config class! \n" . $e->__toString()); } + return $config->remove($category, $key); } } diff --git a/app/Managers/LanguageManager.php b/app/Managers/LanguageManager.php index 22180f3..f12b7d8 100755 --- a/app/Managers/LanguageManager.php +++ b/app/Managers/LanguageManager.php @@ -2,17 +2,14 @@ namespace MythicalSystemsFramework\Managers; -use Exception; -use MythicalSystemsFramework\Kernel\Logger as logger; -use MythicalSystemsFramework\Kernel\LoggerLevels; use MythicalSystemsFramework\Kernel\LoggerTypes; +use MythicalSystemsFramework\Kernel\LoggerLevels; +use MythicalSystemsFramework\Kernel\Logger as logger; class LanguageManager { /** - * Get the language from the file - * - * @return mixed + * Get the language from the file. */ public static function getLang(): mixed { @@ -20,51 +17,54 @@ public static function getLang(): mixed $fallback_lang = __DIR__ . '/../../lang/en_US.php'; if (file_exists($fallback_lang)) { $langConfig = SettingsManager::get('app', 'lang'); - if (!$langConfig == "") { + if (!$langConfig == '') { $langFilePath = __DIR__ . '/../../lang/' . $langConfig . '.php'; if (file_exists($langFilePath)) { - return include($langFilePath); + return include $langFilePath; } else { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::LANGUAGE, "Language file is invalid!!"); - return include($fallback_lang); + logger::log(LoggerLevels::CRITICAL, LoggerTypes::LANGUAGE, 'Language file is invalid!!'); + + return include $fallback_lang; } } else { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::LANGUAGE, "Default language file has not been found in the config!!"); - return include($fallback_lang); + logger::log(LoggerLevels::CRITICAL, LoggerTypes::LANGUAGE, 'Default language file has not been found in the config!!'); + + return include $fallback_lang; } } else { - logger::log(LoggerLevels::CRITICAL, LoggerTypes::LANGUAGE, "Fallback language file has not been found!!"); - die("Fallback language file has not been found!! You are missing important files!"); + logger::log(LoggerLevels::CRITICAL, LoggerTypes::LANGUAGE, 'Fallback language file has not been found!!'); + exit('Fallback language file has not been found!! You are missing important files!'); } - } catch (Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::LANGUAGE, "Error while loading language file: " . $e->getMessage()); - return include($fallback_lang); + } catch (\Exception $e) { + logger::log(LoggerLevels::CRITICAL, LoggerTypes::LANGUAGE, 'Error while loading language file: ' . $e->getMessage()); + + return include $fallback_lang; } } /** - * Get all available languages - * - * @return array + * Get all available languages. */ public static function getAllAvailableLanguages(): array { $langFiles = scandir(__DIR__ . '/../../lang/'); - $langFiles = array_diff($langFiles, array('..', '.')); + $langFiles = array_diff($langFiles, ['..', '.']); + return $langFiles; } /** - * Log translation key not found + * Log translation key not found. * * @param string $key Translation key * @param string $message The alternative message * * @return string The translation key not found message */ - public static function logKeyTranslationNotFound($key, $message = "TRANSLATION_KEY_NOT_FOUND"): string + public static function logKeyTranslationNotFound($key, $message = 'TRANSLATION_KEY_NOT_FOUND'): string { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::LANGUAGE, "Translation key not found: " . $key); + logger::log(LoggerLevels::CRITICAL, LoggerTypes::LANGUAGE, 'Translation key not found: ' . $key); + return $message; } } diff --git a/app/Managers/Settings.php b/app/Managers/Settings.php index c215b7b..62a696c 100755 --- a/app/Managers/Settings.php +++ b/app/Managers/Settings.php @@ -2,11 +2,10 @@ namespace MythicalSystemsFramework\Managers; -use MythicalSystemsFramework\Database\MySQLCache; use MythicalSystemsFramework\Database\MySQL; use MythicalSystemsFramework\Cli\Colors as color; +use MythicalSystemsFramework\Database\MySQLCache; use MythicalSystemsFramework\Managers\exception\settings\NoMigrationsFound; -use Exception; class Settings { @@ -24,45 +23,45 @@ public static function down(): void // No implementation needed for now } - public static function getSetting(string $category, string $name): string|null + public static function getSetting(string $category, string $name): ?string { self::up(); $settings_file = self::$cache_path . '/framework_settings.json'; if (!file_exists($settings_file)) { - MySQLCache::saveCache("framework_settings"); + MySQLCache::saveCache('framework_settings'); } $settings = new \MythicalSystems\Helpers\ConfigHelper($settings_file); self::down(); + return $settings->get($category, $name); } + /** - * Update a setting in the database + * Update a setting in the database. * * @param string $category The name of the category * @param string $name The name of the setting * @param string $value The value you want to replace with! * @param bool $updateCache Update the cache after updating the setting * - * @return void - * @throws Exception + * @throws \Exception */ public static function updateSetting(string $category, string $name, string $value, bool $updateCache = true): void { SettingsManager::update($category, $name, $value); if ($updateCache) { - MySQLCache::saveCache("framework_settings"); + MySQLCache::saveCache('framework_settings'); } } - public static function migrate(bool $isTerminal = false): void { try { $mysql = new MySQL(); $db = $mysql->connectPDO(); - $db->exec("CREATE TABLE IF NOT EXISTS `framework_settings_migrations` (`id` INT NOT NULL AUTO_INCREMENT , `script` TEXT NOT NULL , `executed_at` DATETIME NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB; ALTER TABLE `framework_settings_migrations` CHANGE `executed_at` `executed_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;"); + $db->exec('CREATE TABLE IF NOT EXISTS `framework_settings_migrations` (`id` INT NOT NULL AUTO_INCREMENT , `script` TEXT NOT NULL , `executed_at` DATETIME NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB; ALTER TABLE `framework_settings_migrations` CHANGE `executed_at` `executed_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;'); $phpFiles = glob(__DIR__ . '/../../migrate/config/*.php'); if (count($phpFiles) > 0) { sort($phpFiles); @@ -72,32 +71,32 @@ public static function migrate(bool $isTerminal = false): void foreach ($phpFiles as $phpFile) { $fileName = basename($phpFile); - $stmt = $db->prepare("SELECT COUNT(*) FROM framework_settings_migrations WHERE script = ?"); + $stmt = $db->prepare('SELECT COUNT(*) FROM framework_settings_migrations WHERE script = ?'); $stmt->execute([$fileName]); $count = $stmt->fetchColumn(); if ($count == 0) { include $phpFile; - $stmt = $db->prepare("INSERT INTO framework_settings_migrations (script) VALUES (?)"); + $stmt = $db->prepare('INSERT INTO framework_settings_migrations (script) VALUES (?)'); $stmt->execute([$fileName]); - $migratedCount++; // Increment migrated count + ++$migratedCount; // Increment migrated count } } if ($isTerminal) { - echo color::translateColorsCode("&fMigration completed. Migrated &e" . $migratedCount . " &ffiles."); + echo color::translateColorsCode('&fMigration completed. Migrated &e' . $migratedCount . ' &ffiles.'); } } else { if ($isTerminal) { - echo color::translateColorsCode("&fNo migrations found!"); + echo color::translateColorsCode('&fNo migrations found!'); } } - } catch (Exception $e) { + } catch (\Exception $e) { if ($isTerminal) { - echo color::translateColorsCode("&cFailed to migrate the database: &f" . $e->getMessage() . ""); + echo color::translateColorsCode('&cFailed to migrate the database: &f' . $e->getMessage() . ''); } else { - throw new NoMigrationsFound("No migrations found!". $e->getMessage()); + throw new NoMigrationsFound('No migrations found!' . $e->getMessage()); } } } diff --git a/app/Managers/SettingsManager.php b/app/Managers/SettingsManager.php index 51d19c4..03b91b3 100755 --- a/app/Managers/SettingsManager.php +++ b/app/Managers/SettingsManager.php @@ -19,17 +19,18 @@ class SettingsManager * * @return string|null Incase if found then return the value else return null! */ - public static function get(string $category, string $key): string|null + public static function get(string $category, string $key): ?string { if (self::exists($category, $key)) { $mysql = new MySQL(); $conn = $mysql->connectMYSQLI(); - $stmt = $conn->prepare("SELECT `svalue` FROM framework_settings WHERE `skey` = ? AND `scategory` = ?"); - $stmt->bind_param("ss", $key, $category); + $stmt = $conn->prepare('SELECT `svalue` FROM framework_settings WHERE `skey` = ? AND `scategory` = ?'); + $stmt->bind_param('ss', $key, $category); $stmt->execute(); $stmt->bind_result($value); $stmt->fetch(); $stmt->close(); + return $value; } else { return null; @@ -50,10 +51,11 @@ public static function set(string $category, string $key, string $value): bool { $mysql = new MySQL(); $conn = $mysql->connectMYSQLI(); - $stmt = $conn->prepare("INSERT INTO framework_settings (`scategory`, `skey`, `svalue`) VALUES (?, ?, ?)"); - $stmt->bind_param("sss", $category, $key, $value); + $stmt = $conn->prepare('INSERT INTO framework_settings (`scategory`, `skey`, `svalue`) VALUES (?, ?, ?)'); + $stmt->bind_param('sss', $category, $key, $value); $success = $stmt->execute(); $stmt->close(); + return $success; } @@ -71,10 +73,11 @@ public static function delete(string $category, string $key): bool if (self::exists($category, $key)) { $mysql = new MySQL(); $conn = $mysql->connectMYSQLI(); - $stmt = $conn->prepare("DELETE FROM framework_settings WHERE `skey` = ? AND `scategory` = ?"); - $stmt->bind_param("s", $key); + $stmt = $conn->prepare('DELETE FROM framework_settings WHERE `skey` = ? AND `scategory` = ?'); + $stmt->bind_param('s', $key); $success = $stmt->execute(); $stmt->close(); + return $success; } else { return false; @@ -92,7 +95,8 @@ public static function deleteAll(): bool { $mysql = new MySQL(); $conn = $mysql->connectMYSQLI(); - $success = $conn->query("TRUNCATE TABLE framework_settings"); + $success = $conn->query('TRUNCATE TABLE framework_settings'); + return $success; } @@ -112,10 +116,11 @@ public static function update(string $category, string $key, string $value): boo if (self::exists($category, $key)) { $mysql = new MySQL(); $conn = $mysql->connectMYSQLI(); - $stmt = $conn->prepare("UPDATE framework_settings SET `svalue` = ? WHERE `skey` = ? AND `scategory` = ?"); - $stmt->bind_param("sss", $scategory, $value, $key); + $stmt = $conn->prepare('UPDATE framework_settings SET `svalue` = ? WHERE `skey` = ? AND `scategory` = ?'); + $stmt->bind_param('sss', $scategory, $value, $key); $success = $stmt->execute(); $stmt->close(); + return $success; } else { return false; @@ -136,12 +141,13 @@ public static function exists(string $category, string $key): bool { $mysql = new MySQL(); $conn = $mysql->connectMYSQLI(); - $stmt = $conn->prepare("SELECT COUNT(*) FROM framework_settings WHERE `skey` = ? AND `scategory` = ?"); - $stmt->bind_param("ss", $key, $category); + $stmt = $conn->prepare('SELECT COUNT(*) FROM framework_settings WHERE `skey` = ? AND `scategory` = ?'); + $stmt->bind_param('ss', $key, $category); $stmt->execute(); $stmt->bind_result($count); $stmt->fetch(); $stmt->close(); + return $count > 0; } } diff --git a/app/Managers/SnowFlakeManager.php b/app/Managers/SnowFlakeManager.php index c84cf88..3ac49a9 100755 --- a/app/Managers/SnowFlakeManager.php +++ b/app/Managers/SnowFlakeManager.php @@ -7,7 +7,7 @@ class SnowFlakeManager { /** - * Function to generate a unique user ID + * Function to generate a unique user ID. * * @return string The new user id */ @@ -17,7 +17,7 @@ private static function generateUserID(): string } /** - * Function to get the cached user IDs from the database + * Function to get the cached user IDs from the database. * * @return array Array of cached user IDs */ @@ -25,7 +25,7 @@ private static function getCachedUserIDs(): array { $mysql = new MySQL(); $conn = $mysql->connectMYSQLI(); - $query = "SELECT uid FROM framework_users_userids"; + $query = 'SELECT uid FROM framework_users_userids'; $result = $conn->query($query); $userIds = []; @@ -39,7 +39,7 @@ private static function getCachedUserIDs(): array } /** - * Function to save user IDs to the database + * Function to save user IDs to the database. * * @param string $userId Save the user id inside the database * @@ -49,15 +49,16 @@ private static function saveUserIDToDatabase(string $userId): bool { $mysql = new MySQL(); $conn = $mysql->connectMYSQLI(); - $stmt = $conn->prepare("INSERT INTO framework_users_userids (uid, date) VALUES (?, NOW())"); - $stmt->bind_param("s", $userId); + $stmt = $conn->prepare('INSERT INTO framework_users_userids (uid, date) VALUES (?, NOW())'); + $stmt->bind_param('s', $userId); $success = $stmt->execute(); $stmt->close(); + return $success; } /** - * Function to check if a user ID is already used + * Function to check if a user ID is already used. * * @return bool If this is used or not */ @@ -67,7 +68,7 @@ private static function isUserIDUsed(string $userId, array $cachedUserIds): bool } /** - * Function to get a unique user ID + * Function to get a unique user ID. * * @return string The user id */ @@ -83,12 +84,12 @@ public static function getUniqueUserID(): string if (self::saveUserIDToDatabase($newUserId)) { return $newUserId; } else { - return ""; + return ''; } } /** - * Function to delete a user ID from the database + * Function to delete a user ID from the database. * * @param string $userId The user ID to be deleted from the database * @@ -98,15 +99,16 @@ public static function deleteUserFromDatabase(string $userId): bool { $mysql = new MySQL(); $conn = $mysql->connectMYSQLI(); - $stmt = $conn->prepare("DELETE FROM framework_users_userids WHERE uid = ?"); - $stmt->bind_param("s", $userId); + $stmt = $conn->prepare('DELETE FROM framework_users_userids WHERE uid = ?'); + $stmt->bind_param('s', $userId); $success = $stmt->execute(); $stmt->close(); + return $success; } /** - * Function to check if a user ID exists in the database + * Function to check if a user ID exists in the database. * * @param string $userId The user ID to check * @@ -116,12 +118,13 @@ public static function doesUserExistInDatabase(string $userId): bool { $mysql = new MySQL(); $conn = $mysql->connectMYSQLI(); - $stmt = $conn->prepare("SELECT COUNT(*) FROM framework_users_userids WHERE uid = ?"); - $stmt->bind_param("s", $userId); + $stmt = $conn->prepare('SELECT COUNT(*) FROM framework_users_userids WHERE uid = ?'); + $stmt->bind_param('s', $userId); $stmt->execute(); $stmt->bind_result($count); $stmt->fetch(); $stmt->close(); + return $count > 0; } } diff --git a/app/Managers/exception/settings/NoMigrationsFound.php b/app/Managers/exception/settings/NoMigrationsFound.php index bfa8645..8b2389b 100755 --- a/app/Managers/exception/settings/NoMigrationsFound.php +++ b/app/Managers/exception/settings/NoMigrationsFound.php @@ -2,12 +2,9 @@ namespace MythicalSystemsFramework\Managers\exception\settings; -use Exception; -use Throwable; - -class NoMigrationsFound extends Exception +class NoMigrationsFound extends \Exception { - public function __construct($message = "No migration not found.", $code = 0, Exception $previous = null) + public function __construct($message = 'No migration not found.', $code = 0, ?\Exception $previous = null) { parent::__construct($message, $code, $previous); } diff --git a/app/Plugins/Events/ActivityEvent.php b/app/Plugins/Events/ActivityEvent.php index c315585..f2bd819 100755 --- a/app/Plugins/Events/ActivityEvent.php +++ b/app/Plugins/Events/ActivityEvent.php @@ -15,5 +15,4 @@ public static function OnRemoveUserActivities(): void public static function OnRemoveAllActivities(): void { } - } diff --git a/app/Plugins/Events/AnnouncementEvent.php b/app/Plugins/Events/AnnouncementEvent.php index 1755a4a..0b63059 100755 --- a/app/Plugins/Events/AnnouncementEvent.php +++ b/app/Plugins/Events/AnnouncementEvent.php @@ -27,6 +27,7 @@ public static function OnAnnouncementRemoveDisLike(): void public static function OnAnnouncementRemoveLike(): void { } + public static function OnAnnouncementDisLike(): void { } diff --git a/app/Plugins/Events/ApplicationEvent.php b/app/Plugins/Events/ApplicationEvent.php index 2a11639..1374843 100755 --- a/app/Plugins/Events/ApplicationEvent.php +++ b/app/Plugins/Events/ApplicationEvent.php @@ -11,8 +11,8 @@ public static function OnApplicationDown(): void public static function OnApplicationUp(): void { } + public static function OnApplicationStartup(): void { - } } diff --git a/app/Plugins/Events/ConfigEvent.php b/app/Plugins/Events/ConfigEvent.php index 5c113c7..f9b3833 100755 --- a/app/Plugins/Events/ConfigEvent.php +++ b/app/Plugins/Events/ConfigEvent.php @@ -15,5 +15,4 @@ public static function OnConfigRemove(): void public static function OnConfigUpdate(): void { } - } diff --git a/app/Plugins/Events/CronEvent.php b/app/Plugins/Events/CronEvent.php index d231264..53b5cf8 100755 --- a/app/Plugins/Events/CronEvent.php +++ b/app/Plugins/Events/CronEvent.php @@ -7,5 +7,4 @@ class CronEvent public static function OnCronTabRun(): void { } - } diff --git a/app/Plugins/Events/DatabaseEvent.php b/app/Plugins/Events/DatabaseEvent.php index 9c2202b..8a4a349 100755 --- a/app/Plugins/Events/DatabaseEvent.php +++ b/app/Plugins/Events/DatabaseEvent.php @@ -7,6 +7,7 @@ class DatabaseEvent public static function OnDatabaseConnect(): void { } + public static function OnDatabaseMigration(): void { } diff --git a/app/Plugins/Events/EncryptionEvent.php b/app/Plugins/Events/EncryptionEvent.php index 35b31cc..daeb044 100755 --- a/app/Plugins/Events/EncryptionEvent.php +++ b/app/Plugins/Events/EncryptionEvent.php @@ -11,5 +11,4 @@ public static function OnEncrypt(): void public static function OnDecrypt(): void { } - } diff --git a/app/Plugins/Events/ExceptionEvent.php b/app/Plugins/Events/ExceptionEvent.php index 249d521..2929e7c 100755 --- a/app/Plugins/Events/ExceptionEvent.php +++ b/app/Plugins/Events/ExceptionEvent.php @@ -6,6 +6,5 @@ class ExceptionEvent { public static function OnException(): void { - } } diff --git a/app/Plugins/Events/LoggerEvent.php b/app/Plugins/Events/LoggerEvent.php index 3bc4191..2f4b12e 100755 --- a/app/Plugins/Events/LoggerEvent.php +++ b/app/Plugins/Events/LoggerEvent.php @@ -6,16 +6,13 @@ class LoggerEvent { public static function OnLog(): void { - } public static function onLogsPurge(): void { - } public static function onLogDelete(): void { - } } diff --git a/app/Plugins/Events/NotificationEvent.php b/app/Plugins/Events/NotificationEvent.php index 26ecc49..3955395 100755 --- a/app/Plugins/Events/NotificationEvent.php +++ b/app/Plugins/Events/NotificationEvent.php @@ -15,13 +15,12 @@ public static function OnNotificationEdit(): void public static function OnNotificationDelete(): void { } + public static function OnNotificationDeleteAll(): void { - } public static function OnNotificationRead(): void { } - } diff --git a/app/Plugins/Events/PermissionEvent.php b/app/Plugins/Events/PermissionEvent.php index c03a985..f7624ae 100755 --- a/app/Plugins/Events/PermissionEvent.php +++ b/app/Plugins/Events/PermissionEvent.php @@ -15,5 +15,4 @@ public static function OnPermissionDelete(): void public static function OnPermissionUpdate(): void { } - } diff --git a/app/Plugins/Events/RendererEvent.php b/app/Plugins/Events/RendererEvent.php index 6a60902..76740b8 100755 --- a/app/Plugins/Events/RendererEvent.php +++ b/app/Plugins/Events/RendererEvent.php @@ -6,6 +6,5 @@ class RendererEvent { public static function OnRendererLoad(): void { - } } diff --git a/app/Plugins/Events/RoleEvent.php b/app/Plugins/Events/RoleEvent.php index a0a4738..392533c 100755 --- a/app/Plugins/Events/RoleEvent.php +++ b/app/Plugins/Events/RoleEvent.php @@ -15,5 +15,4 @@ public static function OnRoleDelete(): void public static function OnRoleUpdate(): void { } - } diff --git a/app/Plugins/Events/RouterEvent.php b/app/Plugins/Events/RouterEvent.php index 66bce6e..9c31521 100755 --- a/app/Plugins/Events/RouterEvent.php +++ b/app/Plugins/Events/RouterEvent.php @@ -7,5 +7,4 @@ class RouterEvent public static function OnRouterLoad(): void { } - } diff --git a/app/Plugins/Events/SettingEvent.php b/app/Plugins/Events/SettingEvent.php index af5e01f..3fba623 100755 --- a/app/Plugins/Events/SettingEvent.php +++ b/app/Plugins/Events/SettingEvent.php @@ -18,7 +18,5 @@ public static function OnSettingsSet(): void public static function OnSettingMigration(): void { - } - } diff --git a/app/Plugins/Events/SnowFlakeEvent.php b/app/Plugins/Events/SnowFlakeEvent.php index 3b49f79..dbafdcd 100755 --- a/app/Plugins/Events/SnowFlakeEvent.php +++ b/app/Plugins/Events/SnowFlakeEvent.php @@ -7,5 +7,4 @@ class SnowFlakeEvent public static function OnNewUserID(): void { } - } diff --git a/app/Plugins/Events/UserEvent.php b/app/Plugins/Events/UserEvent.php index 47e5e9b..b286997 100755 --- a/app/Plugins/Events/UserEvent.php +++ b/app/Plugins/Events/UserEvent.php @@ -10,8 +10,9 @@ class UserEvent */ public static function onUserLogin(): void { - //This is where you can add your code to run when a user logs in + // This is where you can add your code to run when a user logs in } + /** * Event: OnUserLogOut * Description: Triggered when a user logs out. @@ -19,6 +20,7 @@ public static function onUserLogin(): void public static function OnUserLogOut(): void { } + /** * Event: OnUserBan * Description: Triggered when a user gets banned. @@ -26,6 +28,7 @@ public static function OnUserLogOut(): void public static function OnUserBan(): void { } + /** * Event: OnUserUnBan * Description: Triggered when a user gets unbanned. @@ -33,6 +36,7 @@ public static function OnUserBan(): void public static function OnUserUnBan(): void { } + /** * Event: OnUserDelete * Description: Triggered when a user gets deleted. @@ -40,6 +44,7 @@ public static function OnUserUnBan(): void public static function OnUserDelete(): void { } + /** * Event: OnUserRestore * Description: Triggered when a user gets undeleted. @@ -47,6 +52,7 @@ public static function OnUserDelete(): void public static function OnUserRestore(): void { } + /** * Event: OnUserVerify * Description: Triggered when a user gets verified. @@ -54,6 +60,7 @@ public static function OnUserRestore(): void public static function OnUserVerify(): void { } + /** * Event: OnUserUnVerify * Description: Triggered when a user needs to verify again. @@ -61,6 +68,7 @@ public static function OnUserVerify(): void public static function OnUserUnVerify(): void { } + /** * Event: OnUserLastSeen * Description: Triggered when a user gets last seen. @@ -68,6 +76,7 @@ public static function OnUserUnVerify(): void public static function OnUserLastSeen(): void { } + /** * Event: OnUserRegister * Description: Triggered when a new user registers. @@ -75,6 +84,7 @@ public static function OnUserLastSeen(): void public static function OnUserRegister(): void { } + /** * Event: OnUserUpdate * Description: Triggered when a user gets updated in the database. diff --git a/app/Plugins/PluginsEventHandler.php b/app/Plugins/PluginsEventHandler.php index 4fa552f..81a9949 100755 --- a/app/Plugins/PluginsEventHandler.php +++ b/app/Plugins/PluginsEventHandler.php @@ -2,15 +2,9 @@ namespace MythicalSystemsFramework\Plugins; -use MythicalSystemsFramework\Plugins\Events\SnowFlakeEvent; -use MythicalSystemsFramework\Plugins\Events\UnitTestEvent; -use MythicalSystemsFramework\Plugins\Events\CronEvent; -use MythicalSystemsFramework\Plugins\Events\PageEvent; - class PluginsEventHandler { public static function registerEvents(): void { - } } diff --git a/app/Plugins/PluginsManager.php b/app/Plugins/PluginsManager.php index 9a068b1..ad1575c 100755 --- a/app/Plugins/PluginsManager.php +++ b/app/Plugins/PluginsManager.php @@ -5,9 +5,7 @@ class PluginsManager { /** - * Get all plugins - * - * @return array + * Get all plugins. */ public static function getAllPlugins(): array { @@ -24,8 +22,6 @@ public static function getAllPlugins(): array $pluginConfigFile = $pluginDir . '/MythicalFramework.json'; $plugins[] = $addonDir; - - } return $plugins; diff --git a/app/Roles/RolesDataHandler.php b/app/Roles/RolesDataHandler.php index f0434bb..26ea4c6 100755 --- a/app/Roles/RolesDataHandler.php +++ b/app/Roles/RolesDataHandler.php @@ -2,32 +2,31 @@ namespace MythicalSystemsFramework\Roles; -use Exception; use MythicalSystemsFramework\Kernel\Logger; -use MythicalSystemsFramework\Kernel\LoggerLevels; use MythicalSystemsFramework\Kernel\LoggerTypes; +use MythicalSystemsFramework\Kernel\LoggerLevels; class RolesDataHandler { /** - * Create a user + * Create a user. * * @param string $name The name of the role * @param int $weight The default is set to 1 * * MAKE SURE YOU CHECK THE DOCS FOR THIS FUNCTION + * * @return string|null The role id in a string */ - public static function create(string $name, int $weight = 1): string|null + public static function create(string $name, int $weight = 1): ?string { try { - - //Connect to the database + // Connect to the database $database = new \MythicalSystemsFramework\Database\MySQL(); $mysqli = $database->connectMYSQLI(); - //Check if the role exists - $stmtRole = $mysqli->prepare("SELECT COUNT(*) FROM framework_roles WHERE name = ?"); - $stmtRole->bind_param("s", $name); + // Check if the role exists + $stmtRole = $mysqli->prepare('SELECT COUNT(*) FROM framework_roles WHERE name = ?'); + $stmtRole->bind_param('s', $name); $stmtRole->execute(); $stmtRole->bind_result($count); @@ -35,108 +34,107 @@ public static function create(string $name, int $weight = 1): string|null $stmtRole->close(); if ($count > 0) { - return "ERROR_ROLE_EXISTS"; + return 'ERROR_ROLE_EXISTS'; } else { - //Insert the role into the database - $stmtInsert = $mysqli->prepare("INSERT INTO framework_roles (name, weight) VALUES (?, ?)"); + // Insert the role into the database + $stmtInsert = $mysqli->prepare('INSERT INTO framework_roles (name, weight) VALUES (?, ?)'); - $stmtInsert->bind_param("si", $name, $weight); + $stmtInsert->bind_param('si', $name, $weight); $stmtInsert->execute(); $stmtInsert->close(); return $mysqli->insert_id; } - } catch (Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/Roles/RolesDataHandler.php) Failed to create role: " . $e->getMessage()); - return "ERROR_DATABASE_INSERT_FAILED"; + } catch (\Exception $e) { + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/Roles/RolesDataHandler.php) Failed to create role: ' . $e->getMessage()); + + return 'ERROR_DATABASE_INSERT_FAILED'; } } /** - * Delete a role + * Delete a role. * * @param int $id The role id * * MAKE SURE YOU CHECK THE DOCS FOR THIS FUNCTION - * @return string|null */ - public static function delete(int $id): string|null + public static function delete(int $id): ?string { try { - if (self::roleExists($id) == "ROLE_MISSING") { - return "ROLE_MISSING"; + if (self::roleExists($id) == 'ROLE_MISSING') { + return 'ROLE_MISSING'; } // Connect to the database $database = new \MythicalSystemsFramework\Database\MySQL(); $mysqli = $database->connectMYSQLI(); // Delete the role - $stmtRole = $mysqli->prepare("DELETE FROM framework_roles WHERE id = ?"); - $stmtRole->bind_param("i", $id); + $stmtRole = $mysqli->prepare('DELETE FROM framework_roles WHERE id = ?'); + $stmtRole->bind_param('i', $id); $stmtRole->execute(); $stmtRole->close(); if ($mysqli->affected_rows > 0) { - return "ROLE_DELETED"; + return 'ROLE_DELETED'; } else { - return "ROLE_DELETE_FAILED"; + return 'ROLE_DELETE_FAILED'; } - } catch (Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/Roles/RolesDataHandler.php) Failed to delete role: " . $e->getMessage()); - return "ERROR_DATABASE_DELETE_FAILED"; + } catch (\Exception $e) { + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/Roles/RolesDataHandler.php) Failed to delete role: ' . $e->getMessage()); + + return 'ERROR_DATABASE_DELETE_FAILED'; } } /** - * Update a role + * Update a role. * * @param int $id The role id * @param string $name The name of the role * @param int $weight The default is set to 1 * * MAKE SURE YOU CHECK THE DOCS FOR THIS FUNCTION - * @return string|null */ - public static function update(int $id, string $name, int $weight = 1): string|null + public static function update(int $id, string $name, int $weight = 1): ?string { try { - if (self::roleExists($id) == "ROLE_MISSING") { - return "ROLE_MISSING"; + if (self::roleExists($id) == 'ROLE_MISSING') { + return 'ROLE_MISSING'; } // Connect to the database $database = new \MythicalSystemsFramework\Database\MySQL(); $mysqli = $database->connectMYSQLI(); // Update the role - $stmtRole = $mysqli->prepare("UPDATE framework_roles SET name = ?, weight = ? WHERE id = ?"); - $stmtRole->bind_param("sii", $name, $weight, $id); + $stmtRole = $mysqli->prepare('UPDATE framework_roles SET name = ?, weight = ? WHERE id = ?'); + $stmtRole->bind_param('sii', $name, $weight, $id); $stmtRole->execute(); $stmtRole->close(); if ($mysqli->affected_rows > 0) { - return "ROLE_UPDATED"; + return 'ROLE_UPDATED'; } else { - return "ROLE_UPDATE_FAILED"; + return 'ROLE_UPDATE_FAILED'; } + } catch (\Exception $e) { + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/Roles/RolesDataHandler.php) Failed to update role: ' . $e->getMessage()); - } catch (Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/Roles/RolesDataHandler.php) Failed to update role: " . $e->getMessage()); - return "ERROR_DATABASE_UPDATE_FAILED"; + return 'ERROR_DATABASE_UPDATE_FAILED'; } } /** - * Get a role + * Get a role. * * @param int $id The role id * @param string $data The data you are looking for * * MAKE SURE YOU CHECK THE DOCS FOR THIS FUNCTION - * @return string|null */ - public static function getSpecificRoleInfo(int $id, string $data): string|null + public static function getSpecificRoleInfo(int $id, string $data): ?string { try { - if (self::roleExists($id) == "ROLE_MISSING") { - return "ROLE_MISSING"; + if (self::roleExists($id) == 'ROLE_MISSING') { + return 'ROLE_MISSING'; } // Connect to the database $database = new \MythicalSystemsFramework\Database\MySQL(); @@ -144,25 +142,26 @@ public static function getSpecificRoleInfo(int $id, string $data): string|null // Get the role info $stmtRole = $mysqli->prepare("SELECT $data FROM framework_roles WHERE id = ?"); - $stmtRole->bind_param("i", $id); + $stmtRole->bind_param('i', $id); $stmtRole->execute(); $stmtRole->bind_result($result); $stmtRole->fetch(); $stmtRole->close(); return $result; - } catch (Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/Roles/RolesDataHandler.php) Failed to get role info: " . $e->getMessage()); - return "ERROR_DATABASE_SELECT_FAILED"; + } catch (\Exception $e) { + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/Roles/RolesDataHandler.php) Failed to get role info: ' . $e->getMessage()); + + return 'ERROR_DATABASE_SELECT_FAILED'; } } /** - * Get all roles with name, weight, and id + * Get all roles with name, weight, and id. * * @return array|null An array of roles with name, weight, and id */ - public static function getAllRoles(): array|null + public static function getAllRoles(): ?array { try { // Connect to the database @@ -170,7 +169,7 @@ public static function getAllRoles(): array|null $mysqli = $database->connectMYSQLI(); // Get all roles - $stmtRoles = $mysqli->prepare("SELECT id, name, weight FROM framework_roles"); + $stmtRoles = $mysqli->prepare('SELECT id, name, weight FROM framework_roles'); $stmtRoles->execute(); $stmtRoles->bind_result($id, $name, $weight); @@ -179,26 +178,26 @@ public static function getAllRoles(): array|null $roles[] = [ 'id' => $id, 'name' => $name, - 'weight' => $weight + 'weight' => $weight, ]; } $stmtRoles->close(); return $roles; - } catch (Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/Roles/RolesDataHandler.php) Failed to get all roles: " . $e->getMessage()); + } catch (\Exception $e) { + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/Roles/RolesDataHandler.php) Failed to get all roles: ' . $e->getMessage()); + return null; } } + /** - * This function just looks if the role exists + * This function just looks if the role exists. * * @param int $id The name of the role - * - * @return string|null */ - public static function roleExists(int $id): string|null + public static function roleExists(int $id): ?string { try { // Connect to the database @@ -206,21 +205,22 @@ public static function roleExists(int $id): string|null $mysqli = $database->connectMYSQLI(); // Check if the role exists - $stmtRole = $mysqli->prepare("SELECT COUNT(*) FROM framework_roles WHERE id = ?"); - $stmtRole->bind_param("i", $id); + $stmtRole = $mysqli->prepare('SELECT COUNT(*) FROM framework_roles WHERE id = ?'); + $stmtRole->bind_param('i', $id); $stmtRole->execute(); $stmtRole->bind_result($count); $stmtRole->fetch(); $stmtRole->close(); if ($count > 0) { - return "ROLE_EXISTS"; + return 'ROLE_EXISTS'; } else { - return "ROLE_MISSING"; + return 'ROLE_MISSING'; } - } catch (Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/Roles/RolesDataHandler.php) Failed to check if role exists: " . $e->getMessage()); - return "ERROR_DATABASE_INSERT_FAILED"; + } catch (\Exception $e) { + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/Roles/RolesDataHandler.php) Failed to check if role exists: ' . $e->getMessage()); + + return 'ERROR_DATABASE_INSERT_FAILED'; } } } diff --git a/app/Roles/RolesHelper.php b/app/Roles/RolesHelper.php index d10d4d4..a29ac9d 100755 --- a/app/Roles/RolesHelper.php +++ b/app/Roles/RolesHelper.php @@ -2,22 +2,15 @@ namespace MythicalSystemsFramework\Roles; -use Exception; -use MythicalSystemsFramework\Kernel\Logger; -use MythicalSystemsFramework\User\UserHelper; - class RolesHelper extends RolesDataHandler { /** - * Get the role name from the role id + * Get the role name from the role id. * * @param string $role_id - * - * @return string|null */ public static function getRoleName(int $role_id): ?string { - return self::getSpecificRoleInfo($role_id, "name"); + return self::getSpecificRoleInfo($role_id, 'name'); } - } diff --git a/app/Roles/RolesPermissionDataHandler.php b/app/Roles/RolesPermissionDataHandler.php index 35be23a..4c0aa49 100755 --- a/app/Roles/RolesPermissionDataHandler.php +++ b/app/Roles/RolesPermissionDataHandler.php @@ -2,22 +2,21 @@ namespace MythicalSystemsFramework\Roles; -use Exception; use MythicalSystemsFramework\Kernel\Logger; -use MythicalSystemsFramework\Kernel\LoggerLevels; use MythicalSystemsFramework\Kernel\LoggerTypes; +use MythicalSystemsFramework\Kernel\LoggerLevels; class RolesPermissionDataHandler { /** - * Create a role permission + * Create a role permission. * * @param int $roleId The role id * @param string $permission The permission * * @return string|null The role permission id in a string */ - public static function create(int $roleId, string $permission): string|null + public static function create(int $roleId, string $permission): ?string { try { // Connect to the database @@ -25,65 +24,63 @@ public static function create(int $roleId, string $permission): string|null $mysqli = $database->connectMYSQLI(); // Insert the role permission into the database - $stmtInsert = $mysqli->prepare("INSERT INTO framework_roles_permissions (role_id, permission) VALUES (?, ?)"); - $stmtInsert->bind_param("is", $roleId, $permission); + $stmtInsert = $mysqli->prepare('INSERT INTO framework_roles_permissions (role_id, permission) VALUES (?, ?)'); + $stmtInsert->bind_param('is', $roleId, $permission); $stmtInsert->execute(); $stmtInsert->close(); return $mysqli->insert_id; - } catch (Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/Roles/RolesPermissionDataHandler.php) Failed to create role permission: " . $e->getMessage()); - return "ERROR_DATABASE_INSERT_FAILED"; + } catch (\Exception $e) { + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/Roles/RolesPermissionDataHandler.php) Failed to create role permission: ' . $e->getMessage()); + + return 'ERROR_DATABASE_INSERT_FAILED'; } } /** - * Delete a role permission + * Delete a role permission. * * @param int $id The role permission id - * - * @return string|null */ - public static function delete(int $id): string|null + public static function delete(int $id): ?string { try { - if (self::rolePermissionExists($id) == "ROLE_PERMISSION_MISSING") { - return "ROLE_PERMISSION_MISSING"; + if (self::rolePermissionExists($id) == 'ROLE_PERMISSION_MISSING') { + return 'ROLE_PERMISSION_MISSING'; } // Connect to the database $database = new \MythicalSystemsFramework\Database\MySQL(); $mysqli = $database->connectMYSQLI(); // Delete the role permission - $stmtRole = $mysqli->prepare("DELETE FROM framework_roles_permissions WHERE id = ?"); - $stmtRole->bind_param("i", $id); + $stmtRole = $mysqli->prepare('DELETE FROM framework_roles_permissions WHERE id = ?'); + $stmtRole->bind_param('i', $id); $stmtRole->execute(); $stmtRole->close(); if ($mysqli->affected_rows > 0) { - return "ROLE_PERMISSION_DELETED"; + return 'ROLE_PERMISSION_DELETED'; } else { - return "ROLE_PERMISSION_DELETE_FAILED"; + return 'ROLE_PERMISSION_DELETE_FAILED'; } - } catch (Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/Roles/RolesPermissionDataHandler.php) Failed to delete role permission: " . $e->getMessage()); - return "ERROR_DATABASE_DELETE_FAILED"; + } catch (\Exception $e) { + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/Roles/RolesPermissionDataHandler.php) Failed to delete role permission: ' . $e->getMessage()); + + return 'ERROR_DATABASE_DELETE_FAILED'; } } /** - * Update a role permission + * Update a role permission. * * @param int $id The role permission id * @param string $permission The permission - * - * @return string|null */ - public static function update(int $id, string $permission): string|null + public static function update(int $id, string $permission): ?string { try { - if (self::rolePermissionExists($id) == "ROLE_PERMISSION_MISSING") { - return "ROLE_PERMISSION_MISSING"; + if (self::rolePermissionExists($id) == 'ROLE_PERMISSION_MISSING') { + return 'ROLE_PERMISSION_MISSING'; } // Connect to the database @@ -91,24 +88,25 @@ public static function update(int $id, string $permission): string|null $mysqli = $database->connectMYSQLI(); // Update the role permission - $stmtRole = $mysqli->prepare("UPDATE framework_roles_permissions SET permission = ? WHERE id = ?"); - $stmtRole->bind_param("si", $permission, $id); + $stmtRole = $mysqli->prepare('UPDATE framework_roles_permissions SET permission = ? WHERE id = ?'); + $stmtRole->bind_param('si', $permission, $id); $stmtRole->execute(); $stmtRole->close(); if ($mysqli->affected_rows > 0) { - return "ROLE_PERMISSION_UPDATED"; + return 'ROLE_PERMISSION_UPDATED'; } else { - return "ROLE_PERMISSION_UPDATE_FAILED"; + return 'ROLE_PERMISSION_UPDATE_FAILED'; } - } catch (Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/Roles/RolesPermissionDataHandler.php) Failed to update role permission: " . $e->getMessage()); - return "ERROR_DATABASE_UPDATE_FAILED"; + } catch (\Exception $e) { + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/Roles/RolesPermissionDataHandler.php) Failed to update role permission: ' . $e->getMessage()); + + return 'ERROR_DATABASE_UPDATE_FAILED'; } } /** - * Get all permissions for a role + * Get all permissions for a role. * * @param int $roleId The role id * @@ -122,13 +120,13 @@ public static function getAllPermissionsForRole(int $roleId): ?array $mysqli = $database->connectMYSQLI(); // Check if the role exists - if (self::rolePermissionExists($roleId) == "ROLE_PERMISSION_MISSING") { + if (self::rolePermissionExists($roleId) == 'ROLE_PERMISSION_MISSING') { return null; } // Get all permissions for the role - $stmtRole = $mysqli->prepare("SELECT permission FROM framework_roles_permissions WHERE role_id = ?"); - $stmtRole->bind_param("i", $roleId); + $stmtRole = $mysqli->prepare('SELECT permission FROM framework_roles_permissions WHERE role_id = ?'); + $stmtRole->bind_param('i', $roleId); $stmtRole->execute(); $stmtRole->bind_result($permission); @@ -140,25 +138,24 @@ public static function getAllPermissionsForRole(int $roleId): ?array $stmtRole->close(); return $permissions; - } catch (Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/Roles/RolesPermissionDataHandler.php) Failed to get permissions for role: " . $e->getMessage()); + } catch (\Exception $e) { + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/Roles/RolesPermissionDataHandler.php) Failed to get permissions for role: ' . $e->getMessage()); + return null; } } /** - * Get a role permission + * Get a role permission. * * @param int $id The role permission id * @param string $data The data you are looking for - * - * @return string|null */ - public static function getSpecificRolePermissionInfo(int $id, string $data): string|null + public static function getSpecificRolePermissionInfo(int $id, string $data): ?string { try { - if (self::rolePermissionExists($id) == "ROLE_PERMISSION_MISSING") { - return "ROLE_PERMISSION_MISSING"; + if (self::rolePermissionExists($id) == 'ROLE_PERMISSION_MISSING') { + return 'ROLE_PERMISSION_MISSING'; } // Connect to the database $database = new \MythicalSystemsFramework\Database\MySQL(); @@ -166,27 +163,26 @@ public static function getSpecificRolePermissionInfo(int $id, string $data): str // Get the role permission info $stmtRole = $mysqli->prepare("SELECT $data FROM framework_roles_permissions WHERE id = ?"); - $stmtRole->bind_param("i", $id); + $stmtRole->bind_param('i', $id); $stmtRole->execute(); $stmtRole->bind_result($result); $stmtRole->fetch(); $stmtRole->close(); return $result; - } catch (Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/Roles/RolesPermissionDataHandler.php) Failed to get role permission info: " . $e->getMessage()); - return "ERROR_DATABASE_SELECT_FAILED"; + } catch (\Exception $e) { + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/Roles/RolesPermissionDataHandler.php) Failed to get role permission info: ' . $e->getMessage()); + + return 'ERROR_DATABASE_SELECT_FAILED'; } } /** - * This function checks if the role permission exists + * This function checks if the role permission exists. * * @param int $id The role permission id - * - * @return string|null */ - public static function rolePermissionExists(int $id): string|null + public static function rolePermissionExists(int $id): ?string { try { // Connect to the database @@ -194,33 +190,32 @@ public static function rolePermissionExists(int $id): string|null $mysqli = $database->connectMYSQLI(); // Check if the role permission exists - $stmtRole = $mysqli->prepare("SELECT COUNT(*) FROM framework_roles_permissions WHERE id = ?"); - $stmtRole->bind_param("i", $id); + $stmtRole = $mysqli->prepare('SELECT COUNT(*) FROM framework_roles_permissions WHERE id = ?'); + $stmtRole->bind_param('i', $id); $stmtRole->execute(); $stmtRole->bind_result($count); $stmtRole->fetch(); $stmtRole->close(); if ($count > 0) { - return "ROLE_PERMISSION_EXISTS"; + return 'ROLE_PERMISSION_EXISTS'; } else { - return "ROLE_PERMISSION_MISSING"; + return 'ROLE_PERMISSION_MISSING'; } - } catch (Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/Roles/RolesPermissionDataHandler.php) Failed to check if role permission exists: " . $e->getMessage()); - return "ERROR_DATABASE_INSERT_FAILED"; + } catch (\Exception $e) { + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/Roles/RolesPermissionDataHandler.php) Failed to check if role permission exists: ' . $e->getMessage()); + + return 'ERROR_DATABASE_INSERT_FAILED'; } } /** - * Check if a role has a specific permission + * Check if a role has a specific permission. * * @param int $roleId The role id * @param string $permission The permission - * - * @return string|null */ - public static function doesRoleHavePermission(int $roleId, string $permission): string|null + public static function doesRoleHavePermission(int $roleId, string $permission): ?string { try { // Connect to the database @@ -228,21 +223,22 @@ public static function doesRoleHavePermission(int $roleId, string $permission): $mysqli = $database->connectMYSQLI(); // Check if the role has the permission - $stmtRole = $mysqli->prepare("SELECT COUNT(*) FROM framework_roles_permissions WHERE role_id = ? AND permission = ?"); - $stmtRole->bind_param("is", $roleId, $permission); + $stmtRole = $mysqli->prepare('SELECT COUNT(*) FROM framework_roles_permissions WHERE role_id = ? AND permission = ?'); + $stmtRole->bind_param('is', $roleId, $permission); $stmtRole->execute(); $stmtRole->bind_result($count); $stmtRole->fetch(); $stmtRole->close(); if ($count > 0) { - return "ROLE_HAS_PERMISSION"; + return 'ROLE_HAS_PERMISSION'; } else { - return "ROLE_DOES_NOT_HAVE_PERMISSION"; + return 'ROLE_DOES_NOT_HAVE_PERMISSION'; } - } catch (Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/Roles/RolesPermissionDataHandler.php) Failed to check role permission: " . $e->getMessage()); - return "ERROR_DATABASE_SELECT_FAILED"; + } catch (\Exception $e) { + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/Roles/RolesPermissionDataHandler.php) Failed to check role permission: ' . $e->getMessage()); + + return 'ERROR_DATABASE_SELECT_FAILED'; } } } diff --git a/app/User/Exceptions/UserException.php b/app/User/Exceptions/UserException.php index 013949e..723fec0 100755 --- a/app/User/Exceptions/UserException.php +++ b/app/User/Exceptions/UserException.php @@ -2,15 +2,13 @@ namespace MythicalSystemsFramework\User\Exceptions; -use Exception; -use Throwable; - -class UserException extends Exception +class UserException extends \Exception { - public function __construct($message, $code = 0, Throwable $previous = null) + public function __construct($message, $code = 0, ?\Throwable $previous = null) { parent::__construct($message, $code, $previous); } + public function __toString(): string { return __CLASS__ . ": [{$this->code}]: {$this->message}\n"; diff --git a/app/User/UserDataHandler.php b/app/User/UserDataHandler.php index 4ce0595..bc0f864 100755 --- a/app/User/UserDataHandler.php +++ b/app/User/UserDataHandler.php @@ -10,40 +10,33 @@ namespace MythicalSystemsFramework\User; -use DateTime; -use Exception; -use MythicalSystemsFramework\Kernel\Encryption as enc; -use MythicalSystemsFramework\Kernel\LoggerLevels; +use Gravatar\Gravatar; use MythicalSystemsFramework\Kernel\LoggerTypes; -use MythicalSystemsFramework\Managers\ConfigManager as cfg; -use MythicalSystemsFramework\Managers\SnowFlakeManager; +use MythicalSystemsFramework\Kernel\LoggerLevels; use MythicalSystemsFramework\Kernel\Logger as logger; -use Gravatar\Gravatar; -use MythicalSystems\User\Cookies; -use MythicalSystemsFramework\Roles\RolesDataHandler; -use MythicalSystemsFramework\Roles\RolesPermissionDataHandler; +use MythicalSystemsFramework\Kernel\Encryption as enc; +use MythicalSystemsFramework\Managers\SnowFlakeManager; class UserDataHandler { /** - * Login a user + * Login a user. * - * @param string $email - * @param string $password * @param string $ip * * MAKE SURE YOU CHECK THE DOCS FOR THIS FUNCTION + * * @return string|null The user token */ - public static function login(string $email, string $password, string $ip): string|null + public static function login(string $email, string $password, string $ip): ?string { try { - //Connect to the database + // Connect to the database $database = new \MythicalSystemsFramework\Database\MySQL(); $mysqli = $database->connectMYSQLI(); - //Check if the user exists - $stmt = $mysqli->prepare("SELECT COUNT(*) FROM framework_users WHERE email = ? OR username = ?"); - $stmt->bind_param("ss", $email, $email); + // Check if the user exists + $stmt = $mysqli->prepare('SELECT COUNT(*) FROM framework_users WHERE email = ? OR username = ?'); + $stmt->bind_param('ss', $email, $email); $stmt->execute(); $stmt->bind_result($count); @@ -51,72 +44,71 @@ public static function login(string $email, string $password, string $ip): strin $stmt->close(); if ($count == 0) { - return "ERROR_USER_NOT_FOUND"; + return 'ERROR_USER_NOT_FOUND'; } else { - //Get the user data - $stmt = $mysqli->prepare("SELECT password token FROM framework_users WHERE email = ?"); - $stmt->bind_param("s", $email); + // Get the user data + $stmt = $mysqli->prepare('SELECT password token FROM framework_users WHERE email = ?'); + $stmt->bind_param('s', $email); $stmt->execute(); $stmt->bind_result($db_password, $token); $stmt->fetch(); $stmt->close(); - //Check if the password is correct + // Check if the password is correct if (enc::decrypt($db_password) == $password) { - if (UserHelper::isUserBanned($token) == "USER_BANNED") { - return "ERROR_USER_BANNED"; + if (UserHelper::isUserBanned($token) == 'USER_BANNED') { + return 'ERROR_USER_BANNED'; } - if (UserHelper::isUserDeleted($token) == "USER_DELETED") { - return "ERROR_USER_DELETED"; + if (UserHelper::isUserDeleted($token) == 'USER_DELETED') { + return 'ERROR_USER_DELETED'; } - if (UserHelper::isUserVerified($token) == "USER_NOT_VERIFIED") { - return "ERROR_USER_NOT_VERIFIED"; + if (UserHelper::isUserVerified($token) == 'USER_NOT_VERIFIED') { + return 'ERROR_USER_NOT_VERIFIED'; } - //Update the last ip - $stmt = $mysqli->prepare("UPDATE framework_users SET last_ip = ? WHERE email = ?"); - $stmt->bind_param("ss", $ip, $email); + // Update the last ip + $stmt = $mysqli->prepare('UPDATE framework_users SET last_ip = ? WHERE email = ?'); + $stmt->bind_param('ss', $ip, $email); $stmt->execute(); $stmt->close(); // Update last seen! UserHelper::updateLastSeen($token, $ip); + return $token; } else { - return "ERROR_PASSWORD_INCORRECT"; + return 'ERROR_PASSWORD_INCORRECT'; } } } catch (\Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/User/UserDataHandler.php) Failed to login user: " . $e->getMessage()); - return "ERROR_DATABASE_SELECT_FAILED"; + logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/User/UserDataHandler.php) Failed to login user: ' . $e->getMessage()); + + return 'ERROR_DATABASE_SELECT_FAILED'; } } + /** - * Create a user + * Create a user. * - * @param string $username - * @param string $password - * @param string $email - * @param string $first_name - * @param string $last_name * @param string $ip * * MAKE SURE YOU CHECK THE DOCS FOR THIS FUNCTION + * * @return string|null The user token */ - public static function create(string $username, string $password, string $email, string $first_name, string $last_name, string $ip): string|null + public static function create(string $username, string $password, string $email, string $first_name, string $last_name, string $ip): ?string { try { $username = enc::encrypt($username); $email = enc::encrypt($email); - //Connect to the database + // Connect to the database $database = new \MythicalSystemsFramework\Database\MySQL(); $mysqli = $database->connectMYSQLI(); - //New gravatar instance for avatars! + // New gravatar instance for avatars! $gravatar = new Gravatar([], true); - //Check if the username exists - $stmtUsername = $mysqli->prepare("SELECT COUNT(*) FROM framework_users WHERE username = ?"); - $stmtUsername->bind_param("s", $username); + // Check if the username exists + $stmtUsername = $mysqli->prepare('SELECT COUNT(*) FROM framework_users WHERE username = ?'); + $stmtUsername->bind_param('s', $username); $stmtUsername->execute(); $stmtUsername->bind_result($count); @@ -124,31 +116,31 @@ public static function create(string $username, string $password, string $email, $stmtUsername->close(); if ($count > 0) { - return "ERROR_USERNAME_EXISTS"; + return 'ERROR_USERNAME_EXISTS'; } else { - //Check if the email exists - $stmtEmail = $mysqli->prepare("SELECT COUNT(*) FROM framework_users WHERE email = ?"); - $stmtEmail->bind_param("s", $email); + // Check if the email exists + $stmtEmail = $mysqli->prepare('SELECT COUNT(*) FROM framework_users WHERE email = ?'); + $stmtEmail->bind_param('s', $email); $stmtEmail->execute(); $stmtEmail->bind_result($emailCount); $stmtEmail->fetch(); $stmtEmail->close(); if ($emailCount > 0) { - return "ERROR_EMAIL_EXISTS"; + return 'ERROR_EMAIL_EXISTS'; } else { - //Insert the user into the database - $stmtInsert = $mysqli->prepare("INSERT INTO framework_users (username, first_name, last_name, email, password, avatar, uuid, token, first_ip, last_ip) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); - //Hash the password + // Insert the user into the database + $stmtInsert = $mysqli->prepare('INSERT INTO framework_users (username, first_name, last_name, email, password, avatar, uuid, token, first_ip, last_ip) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'); + // Hash the password $password = enc::encrypt($password); - //Generate a unic user id! UUID - $uuid = SnowflakeManager::getUniqueUserID(); - $account_token = "mythicalframework_" . base64_encode($uuid . '_' . DateTime::createFromFormat('U.u', microtime(true))->format("Y-m-d H:i:s.u") . rand(1000, 9999) . $ip . enc::encrypt($email)); + // Generate a unic user id! UUID + $uuid = SnowFlakeManager::getUniqueUserID(); + $account_token = 'mythicalframework_' . base64_encode($uuid . '_' . \DateTime::createFromFormat('U.u', microtime(true))->format('Y-m-d H:i:s.u') . mt_rand(1000, 9999) . $ip . enc::encrypt($email)); $avatar_url = $gravatar->avatar(enc::decrypt($email)); $first_name = enc::encrypt($first_name); $last_name = enc::encrypt($last_name); $ip = enc::encrypt($ip); - $stmtInsert->bind_param("ssssssssss", $username, $first_name, $last_name, $email, $password, $avatar_url, $uuid, $account_token, $ip, $ip); + $stmtInsert->bind_param('ssssssssss', $username, $first_name, $last_name, $email, $password, $avatar_url, $uuid, $account_token, $ip, $ip); $stmtInsert->execute(); $stmtInsert->close(); @@ -156,13 +148,14 @@ public static function create(string $username, string $password, string $email, } } } catch (\Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/User/UserDataHandler.php) Failed to create user: " . $e->getMessage()); - return "ERROR_DATABASE_INSERT_FAILED"; + logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/User/UserDataHandler.php) Failed to create user: ' . $e->getMessage()); + + return 'ERROR_DATABASE_INSERT_FAILED'; } } /** - * Get the user data + * Get the user data. * * @param string $account_token The token of the account you want the data for! * @param string $data The data you want to get from the user! @@ -170,19 +163,19 @@ public static function create(string $username, string $password, string $email, * * @return string The user data or null if not found! */ - public static function getSpecificUserData(string $account_token, string $data, bool $encrypted = true): string|null + public static function getSpecificUserData(string $account_token, string $data, bool $encrypted = true): ?string { try { $isAccountValid = UserHelper::isSessionValid($account_token); if (!$isAccountValid) { - return "ERROR_ACCOUNT_NOT_VALID"; + return 'ERROR_ACCOUNT_NOT_VALID'; } - //Connect to the database + // Connect to the database $database = new \MythicalSystemsFramework\Database\MySQL(); $mysqli = $database->connectMYSQLI(); - //Check if the user exists - $stmt = $mysqli->prepare("SELECT * FROM framework_users WHERE token = ?"); - $stmt->bind_param("s", $account_token); + // Check if the user exists + $stmt = $mysqli->prepare('SELECT * FROM framework_users WHERE token = ?'); + $stmt->bind_param('s', $account_token); $stmt->execute(); $result = $stmt->get_result(); $user = $result->fetch_assoc(); @@ -194,16 +187,17 @@ public static function getSpecificUserData(string $account_token, string $data, return $user[$data]; } } else { - return "ERROR_FIELD_NOT_FOUND"; + return 'ERROR_FIELD_NOT_FOUND'; } } catch (\Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/User/UserDataHandler.php) Failed to get user data: " . $e->getMessage()); - return "ERROR_DATABASE_SELECT_FAILED"; + logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/User/UserDataHandler.php) Failed to get user data: ' . $e->getMessage()); + + return 'ERROR_DATABASE_SELECT_FAILED'; } } /** - * Update the user data + * Update the user data. * * @param string $account_token The token of the account you want to update the data for! * @param string $data The data you want to update! @@ -217,24 +211,25 @@ public static function updateSpecificUserData(string $account_token, string $dat try { $isAccountValid = UserHelper::isSessionValid($account_token); if (!$isAccountValid) { - return "ERROR_ACCOUNT_NOT_VALID"; + return 'ERROR_ACCOUNT_NOT_VALID'; } - //Connect to the database + // Connect to the database $database = new \MythicalSystemsFramework\Database\MySQL(); $mysqli = $database->connectMYSQLI(); - //Check if the user exists + // Check if the user exists $stmt = $mysqli->prepare("UPDATE framework_users SET $data = ? WHERE token = ?"); if ($encrypted) { $value = enc::encrypt($value); } - $stmt->bind_param("ss", $value, $account_token); + $stmt->bind_param('ss', $value, $account_token); $stmt->execute(); $stmt->close(); - return "SUCCESS"; + + return 'SUCCESS'; } catch (\Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/User/UserDataHandler.php) Failed to update user: " . $e->getMessage()); - return "ERROR_DATABASE_UPDATE_FAILED"; + logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/User/UserDataHandler.php) Failed to update user: ' . $e->getMessage()); + + return 'ERROR_DATABASE_UPDATE_FAILED'; } } - } diff --git a/app/User/UserHelper.php b/app/User/UserHelper.php index 88290c2..25f6c88 100755 --- a/app/User/UserHelper.php +++ b/app/User/UserHelper.php @@ -6,11 +6,10 @@ namespace MythicalSystemsFramework\User; -use Exception; use MythicalSystems\User\Cookies; use MythicalSystemsFramework\Kernel\Logger; -use MythicalSystemsFramework\Kernel\LoggerLevels; use MythicalSystemsFramework\Kernel\LoggerTypes; +use MythicalSystemsFramework\Kernel\LoggerLevels; use MythicalSystemsFramework\Roles\RolesDataHandler; use MythicalSystemsFramework\Roles\RolesPermissionDataHandler; @@ -19,83 +18,86 @@ class UserHelper extends UserDataHandler /** * This function will ban a user from the system. * - * @param string $account_token The account token of the user you want to ban. + * @param string $account_token the account token of the user you want to ban * - * @return string The response of the ban. + * @return string the response of the ban */ public static function banUser(string $account_token): string { try { if (self::isSessionValid($account_token)) { - $update_user = self::updateSpecificUserData($account_token, "banned", "YES", false); - if ($update_user == "SUCCESS") { - return "USER_BANNED"; + $update_user = self::updateSpecificUserData($account_token, 'banned', 'YES', false); + if ($update_user == 'SUCCESS') { + return 'USER_BANNED'; } else { - return "ERROR_DATABASE_UPDATE_FAILED"; + return 'ERROR_DATABASE_UPDATE_FAILED'; } } else { - return "ERROR_ACCOUNT_NOT_VALID"; + return 'ERROR_ACCOUNT_NOT_VALID'; } } catch (\Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/User/UserHelper.php) Failed to ban user: " . $e->getMessage()); - return "ERROR_DATABASE_UPDATE_FAILED"; + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/User/UserHelper.php) Failed to ban user: ' . $e->getMessage()); + + return 'ERROR_DATABASE_UPDATE_FAILED'; } } /** * This function will unban a user from the system. * - * @param string $account_token The account token of the user you want to unban. + * @param string $account_token the account token of the user you want to unban * - * @return string The response of the unban. + * @return string the response of the unban */ public static function unbanUser(string $account_token): string { try { if (self::isSessionValid($account_token)) { - $update_user = self::updateSpecificUserData($account_token, "banned", "NO", false); - if ($update_user == "SUCCESS") { - return "USER_UNBANNED"; + $update_user = self::updateSpecificUserData($account_token, 'banned', 'NO', false); + if ($update_user == 'SUCCESS') { + return 'USER_UNBANNED'; } else { - return "ERROR_DATABASE_UPDATE_FAILED"; + return 'ERROR_DATABASE_UPDATE_FAILED'; } } else { - return "ERROR_ACCOUNT_NOT_VALID"; + return 'ERROR_ACCOUNT_NOT_VALID'; } } catch (\Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/User/UserHelper.php) Failed to unban user: " . $e->getMessage()); - return "ERROR_DATABASE_UPDATE_FAILED"; + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/User/UserHelper.php) Failed to unban user: ' . $e->getMessage()); + + return 'ERROR_DATABASE_UPDATE_FAILED'; } } /** * This function will check if the user is banned. * - * @param string $account_token The account token of the user you want to check. + * @param string $account_token the account token of the user you want to check * - * @return string If the user is banned or not. + * @return string if the user is banned or not */ public static function isUserBanned(string $account_token): string { try { if (self::isSessionValid($account_token)) { - $ban_state = self::getSpecificUserData($account_token, "banned", false); - if ($ban_state == "NO") { - return "USER_NOT_BANNED"; + $ban_state = self::getSpecificUserData($account_token, 'banned', false); + if ($ban_state == 'NO') { + return 'USER_NOT_BANNED'; } else { - return "USER_BANNED"; + return 'USER_BANNED'; } } else { - return "ERROR_ACCOUNT_NOT_VALID"; + return 'ERROR_ACCOUNT_NOT_VALID'; } } catch (\Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/User/UserHelper.php) Failed to check if user is banned: " . $e->getMessage()); - return "ERROR_DATABASE_SELECT_FAILED"; + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/User/UserHelper.php) Failed to check if user is banned: ' . $e->getMessage()); + + return 'ERROR_DATABASE_SELECT_FAILED'; } } /** - * Check if the user session is valid + * Check if the user session is valid. * * @param string $account_token The token of the account you want the check the session for! * @@ -104,12 +106,12 @@ public static function isUserBanned(string $account_token): string public static function isSessionValid(string $account_token): bool { try { - //Connect to the database + // Connect to the database $database = new \MythicalSystemsFramework\Database\MySQL(); $mysqli = $database->connectMYSQLI(); - //Check if the user exists - $stmt = $mysqli->prepare("SELECT COUNT(*) FROM framework_users WHERE token = ?"); - $stmt->bind_param("s", $account_token); + // Check if the user exists + $stmt = $mysqli->prepare('SELECT COUNT(*) FROM framework_users WHERE token = ?'); + $stmt->bind_param('s', $account_token); $stmt->execute(); $stmt->bind_result($count); @@ -122,260 +124,267 @@ public static function isSessionValid(string $account_token): bool return true; } } catch (\Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/User/UserDataHandler.php) Failed to validate user: " . $e->getMessage()); + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/User/UserDataHandler.php) Failed to validate user: ' . $e->getMessage()); + return false; } } /** - * Log the user out of his account + * Log the user out of his account. * * @return void This functions removes the token header! */ public static function killSession(): void { - //Kill the session + // Kill the session session_destroy(); - setcookie("token", "", time() - 3600); - Cookies::unSetCookie("token"); + setcookie('token', '', time() - 3600); + Cookies::unSetCookie('token'); } /** - * This function will soft delete a user + * This function will soft delete a user. * - * @param string $account_token The account token of the user you want to delete. + * @param string $account_token the account token of the user you want to delete * - * @return string The response of the delete. + * @return string the response of the delete */ public static function deleteUser(string $account_token): string { try { if (self::isSessionValid($account_token)) { - $update_user = self::updateSpecificUserData($account_token, "deleted", "true", false); - if ($update_user == "SUCCESS") { - return "USER_DELETED"; + $update_user = self::updateSpecificUserData($account_token, 'deleted', 'true', false); + if ($update_user == 'SUCCESS') { + return 'USER_DELETED'; } else { - return "ERROR_DATABASE_UPDATE_FAILED"; + return 'ERROR_DATABASE_UPDATE_FAILED'; } } else { - return "ERROR_ACCOUNT_NOT_VALID"; + return 'ERROR_ACCOUNT_NOT_VALID'; } } catch (\Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/User/UserHelper.php) Failed to delete user: " . $e->getMessage()); - return "ERROR_DATABASE_UPDATE_FAILED"; + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/User/UserHelper.php) Failed to delete user: ' . $e->getMessage()); + + return 'ERROR_DATABASE_UPDATE_FAILED'; } } /** - * This function will restore a soft deleted user + * This function will restore a soft deleted user. * - * @param string $account_token The account token of the user you want to restore. + * @param string $account_token the account token of the user you want to restore * - * @return string The response of the restore. + * @return string the response of the restore */ public static function restoreUser(string $account_token): string { try { if (self::isSessionValid($account_token)) { - $update_user = self::updateSpecificUserData($account_token, "deleted", "false", false); - if ($update_user == "SUCCESS") { - return "USER_RESTORED"; + $update_user = self::updateSpecificUserData($account_token, 'deleted', 'false', false); + if ($update_user == 'SUCCESS') { + return 'USER_RESTORED'; } else { - return "ERROR_DATABASE_UPDATE_FAILED"; + return 'ERROR_DATABASE_UPDATE_FAILED'; } } else { - return "ERROR_ACCOUNT_NOT_VALID"; + return 'ERROR_ACCOUNT_NOT_VALID'; } } catch (\Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/User/UserHelper.php) Failed to restore user: " . $e->getMessage()); - return "ERROR_DATABASE_UPDATE_FAILED"; + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/User/UserHelper.php) Failed to restore user: ' . $e->getMessage()); + + return 'ERROR_DATABASE_UPDATE_FAILED'; } } /** - * This function will check if the user is soft deleted + * This function will check if the user is soft deleted. * - * @param string $account_token The account token of the user you want to check. + * @param string $account_token the account token of the user you want to check * - * @return string The response of the check. + * @return string the response of the check */ public static function isUserDeleted(string $account_token): string { try { if (self::isSessionValid($account_token)) { - $delete_state = self::getSpecificUserData($account_token, "deleted", false); - if ($delete_state == "false") { - return "USER_NOT_DELETED"; + $delete_state = self::getSpecificUserData($account_token, 'deleted', false); + if ($delete_state == 'false') { + return 'USER_NOT_DELETED'; } else { - return "USER_DELETED"; + return 'USER_DELETED'; } } else { - return "ERROR_ACCOUNT_NOT_VALID"; + return 'ERROR_ACCOUNT_NOT_VALID'; } } catch (\Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/User/UserHelper.php) Failed to check if user is deleted: " . $e->getMessage()); - return "ERROR_DATABASE_SELECT_FAILED"; + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/User/UserHelper.php) Failed to check if user is deleted: ' . $e->getMessage()); + + return 'ERROR_DATABASE_SELECT_FAILED'; } } /** - * This function will check if the user is verified + * This function will check if the user is verified. * - * @param string $account_token The account token of the user you want to check. + * @param string $account_token the account token of the user you want to check * - * @return string The response of the check. + * @return string the response of the check */ public static function isUserVerified(string $account_token): string { try { if (self::isSessionValid($account_token)) { - $verified_state = self::getSpecificUserData($account_token, "verified", false); - if ($verified_state == "false") { - return "USER_NOT_VERIFIED"; + $verified_state = self::getSpecificUserData($account_token, 'verified', false); + if ($verified_state == 'false') { + return 'USER_NOT_VERIFIED'; } else { - return "USER_VERIFIED"; + return 'USER_VERIFIED'; } } else { - return "ERROR_ACCOUNT_NOT_VALID"; + return 'ERROR_ACCOUNT_NOT_VALID'; } } catch (\Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/User/UserHelper.php) Failed to check if user is verified: " . $e->getMessage()); - return "ERROR_DATABASE_SELECT_FAILED"; + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/User/UserHelper.php) Failed to check if user is verified: ' . $e->getMessage()); + + return 'ERROR_DATABASE_SELECT_FAILED'; } } /** - * This function will verify a user + * This function will verify a user. * - * @param string $account_token The account token of the user you want to verify. + * @param string $account_token the account token of the user you want to verify * - * @return string The response of the verification. + * @return string the response of the verification */ public static function verifyUser(string $account_token): string { try { if (self::isSessionValid($account_token)) { - $update_user = self::updateSpecificUserData($account_token, "verified", "true", false); - if ($update_user == "SUCCESS") { - return "USER_VERIFIED"; + $update_user = self::updateSpecificUserData($account_token, 'verified', 'true', false); + if ($update_user == 'SUCCESS') { + return 'USER_VERIFIED'; } else { - return "ERROR_DATABASE_UPDATE_FAILED"; + return 'ERROR_DATABASE_UPDATE_FAILED'; } } else { - return "ERROR_ACCOUNT_NOT_VALID"; + return 'ERROR_ACCOUNT_NOT_VALID'; } } catch (\Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/User/UserHelper.php) Failed to verify user: " . $e->getMessage()); - return "ERROR_DATABASE_UPDATE_FAILED"; + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/User/UserHelper.php) Failed to verify user: ' . $e->getMessage()); + + return 'ERROR_DATABASE_UPDATE_FAILED'; } } /** - * This function will unverify a user + * This function will unverify a user. * - * @param string $account_token The account token of the user you want to unverify. + * @param string $account_token the account token of the user you want to unverify * - * @return string The response of the unverification. + * @return string the response of the unverification */ public static function unverifyUser(string $account_token): string { try { if (self::isSessionValid($account_token)) { - $update_user = self::updateSpecificUserData($account_token, "verified", "false", false); - if ($update_user == "SUCCESS") { - return "USER_UNVERIFIED"; + $update_user = self::updateSpecificUserData($account_token, 'verified', 'false', false); + if ($update_user == 'SUCCESS') { + return 'USER_UNVERIFIED'; } else { - return "ERROR_DATABASE_UPDATE_FAILED"; + return 'ERROR_DATABASE_UPDATE_FAILED'; } } else { - return "ERROR_ACCOUNT_NOT_VALID"; + return 'ERROR_ACCOUNT_NOT_VALID'; } } catch (\Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/User/UserHelper.php) Failed to unverify user: " . $e->getMessage()); - return "ERROR_DATABASE_UPDATE_FAILED"; + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/User/UserHelper.php) Failed to unverify user: ' . $e->getMessage()); + + return 'ERROR_DATABASE_UPDATE_FAILED'; } } /** - * This function will update the last seen and the last ip of the user - * - * @param string $account_token The account token of the user you want to update. - * @param string $ip The ip of the user. + * This function will update the last seen and the last ip of the user. * - * @return string + * @param string $account_token the account token of the user you want to update + * @param string $ip the ip of the user */ public static function updateLastSeen(string $account_token, string $ip): string { try { if (self::isSessionValid($account_token)) { - $update_user = self::updateSpecificUserData($account_token, "last_seen", date("Y-m-d H:i:s"), false); - if ($update_user == "SUCCESS") { - $update_user = self::updateSpecificUserData($account_token, "last_ip", $ip, false); - if ($update_user == "SUCCESS") { - return "SUCCESS"; + $update_user = self::updateSpecificUserData($account_token, 'last_seen', date('Y-m-d H:i:s'), false); + if ($update_user == 'SUCCESS') { + $update_user = self::updateSpecificUserData($account_token, 'last_ip', $ip, false); + if ($update_user == 'SUCCESS') { + return 'SUCCESS'; } else { - return "ERROR_DATABASE_UPDATE_FAILED"; + return 'ERROR_DATABASE_UPDATE_FAILED'; } } else { - return "ERROR_DATABASE_UPDATE_FAILED"; + return 'ERROR_DATABASE_UPDATE_FAILED'; } } else { - return "ERROR_ACCOUNT_NOT_VALID"; + return 'ERROR_ACCOUNT_NOT_VALID'; } } catch (\Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/User/UserHelper.php) Failed to update last seen: " . $e->getMessage()); - return "ERROR_DATABASE_UPDATE_FAILED"; + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/User/UserHelper.php) Failed to update last seen: ' . $e->getMessage()); + + return 'ERROR_DATABASE_UPDATE_FAILED'; } } /** - * This function will return your the role id of a user + * This function will return your the role id of a user. * - * @param string $account_token The account token of the user you want to get the role id from. + * @param string $account_token the account token of the user you want to get the role id from * - * @return string|null The role id of the user or an error. + * @return string|null the role id of the user or an error */ - public static function getUserRoleId($account_token): string|null + public static function getUserRoleId($account_token): ?string { try { if (self::isSessionValid($account_token)) { - $role_id = self::getSpecificUserData($account_token, "role", false); + $role_id = self::getSpecificUserData($account_token, 'role', false); + return $role_id; } else { - return "ERROR_ACCOUNT_NOT_VALID"; + return 'ERROR_ACCOUNT_NOT_VALID'; } - } catch (Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/User/UserHelper.php) Failed to get user role id: " . $e->getMessage()); - return "ERROR_DATABASE_SELECT_FAILED"; + } catch (\Exception $e) { + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/User/UserHelper.php) Failed to get user role id: ' . $e->getMessage()); + + return 'ERROR_DATABASE_SELECT_FAILED'; } } /** * Does this user have permission? * - * @param string $account_token The account token. - * @param string $permission The permission name. - * - * @return string|null + * @param string $account_token the account token + * @param string $permission the permission name */ - public static function doesUserHavePermission(string $account_token, string $permission): string|null + public static function doesUserHavePermission(string $account_token, string $permission): ?string { try { - $role_id = UserHelper::getSpecificUserData($account_token, "role", false); + $role_id = UserHelper::getSpecificUserData($account_token, 'role', false); $role_check = RolesDataHandler::roleExists($role_id); - if ($role_check == "ROLE_EXISTS") { + if ($role_check == 'ROLE_EXISTS') { $permission_check = RolesPermissionDataHandler::doesRoleHavePermission($role_id, $permission); - if ($permission_check == "ROLE_HAS_PERMISSION") { - return "USER_HAS_PERMISSION"; + if ($permission_check == 'ROLE_HAS_PERMISSION') { + return 'USER_HAS_PERMISSION'; } else { return $permission_check; } } else { return $role_check; } - } catch (Exception $e) { - Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, "(App/User/UserHelper.php) Failed to get role info: " . $e->getMessage()); - return "ERROR_DATABASE_SELECT_FAILED"; + } catch (\Exception $e) { + Logger::log(LoggerLevels::CRITICAL, LoggerTypes::DATABASE, '(App/User/UserHelper.php) Failed to get role info: ' . $e->getMessage()); + + return 'ERROR_DATABASE_SELECT_FAILED'; } } } diff --git a/commands/core/cache/cacheprocess.php b/commands/core/cache/cacheprocess.php index fb42b00..266d031 100755 --- a/commands/core/cache/cacheprocess.php +++ b/commands/core/cache/cacheprocess.php @@ -1,20 +1,18 @@ getMessage()); + echo color::translateColorsCode('&rProcessed caches!'); + } catch (Exception $e) { + echo color::translateColorsCode('&cFailed to process caches: &r' . $e->getMessage()); } } } diff --git a/commands/core/cache/cachepurge.php b/commands/core/cache/cachepurge.php index d188083..4a691bb 100755 --- a/commands/core/cache/cachepurge.php +++ b/commands/core/cache/cachepurge.php @@ -1,20 +1,18 @@ getMessage()); + echo color::translateColorsCode('&rPurged caches!'); + } catch (Exception $e) { + echo color::translateColorsCode('&cFailed to purge caches: &r' . $e->getMessage()); } } } diff --git a/commands/core/encryption/newkey.php b/commands/core/encryption/newkey.php index 461be47..f7dac84 100755 --- a/commands/core/encryption/newkey.php +++ b/commands/core/encryption/newkey.php @@ -7,27 +7,25 @@ class newkeyCommand { public function execute() { - if (cfg::get("encryption", "key") == "") { + if (cfg::get('encryption', 'key') == '') { $this->generate(); } else { - echo color::translateColorsCode("&4&lWARNING: &fA key already exists. Do you want to generate a new one?&o"); - echo color::translateColorsCode("&4&lWARNING: &fGenerating a new key will make all encrypted data unreadable. &o"); - echo color::translateColorsCode("&4&lWARNING: &fType &ey&f to continue or &en&f to exit:"); + echo color::translateColorsCode('&4&lWARNING: &fA key already exists. Do you want to generate a new one?&o'); + echo color::translateColorsCode('&4&lWARNING: &fGenerating a new key will make all encrypted data unreadable. &o'); + echo color::translateColorsCode('&4&lWARNING: &fType &ey&f to continue or &en&f to exit:'); $confirm = readline(); if (strtolower($confirm) === 'y') { $this->generate(); } else { - die(color::translateColorsCode("&fExiting...&o")); + exit(color::translateColorsCode('&fExiting...&o')); } } } - /** - * - */ + public function generate() { - $key = "mythicalcore_".bin2hex(random_bytes(64 * 32)); - cfg::set("encryption", "key", $key); - echo color::translateColorsCode("&fKey generated successfully!&o"); + $key = 'mythicalcore_' . bin2hex(random_bytes(64 * 32)); + cfg::set('encryption', 'key', $key); + echo color::translateColorsCode('&fKey generated successfully!&o'); } } diff --git a/composer.json b/composer.json index 3de5a65..99441bd 100755 --- a/composer.json +++ b/composer.json @@ -86,7 +86,7 @@ ], "lint": [ "export COMPOSER_ALLOW_SUPERUSER=1", - "vendor/bin/php-cs-fixer fix ." + "vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.dist.php" ] } } diff --git a/cron/jobs/SettingsJob.php b/cron/jobs/SettingsJob.php index 3765154..b08bb8e 100755 --- a/cron/jobs/SettingsJob.php +++ b/cron/jobs/SettingsJob.php @@ -1,8 +1,6 @@ getMessage()); + exit('Failed to migrate the database: ' . $e->getMessage()); } catch (NoMigrationsFound $e) { - die("No migrations found!"); + exit('No migrations found!'); } catch (Exception $e) { - die("Failed to migrate the database: " . $e->getMessage()); + exit('Failed to migrate the database: ' . $e->getMessage()); } migrateCfg(); settings::update('app', 'name', $app_name); @@ -79,19 +78,19 @@ settings::update('app', 'logo', $settings_app_logo); try { unlink(__DIR__ . '/../FIRST_INSTALL'); - die("OK_DEL_FIRST_INSTALL"); + exit('OK_DEL_FIRST_INSTALL'); } catch (Exception $e) { - die("OK_DEL_FIRST_INSTALL"); + exit('OK_DEL_FIRST_INSTALL'); } } catch (Exception $e) { - die("Failed to migrate the database: " . $e->getMessage()); + exit('Failed to migrate the database: ' . $e->getMessage()); } } catch (Exception $e) { - die("Failed to configure the database: " . $e->getMessage()); + exit('Failed to configure the database: ' . $e->getMessage()); } /** - * Install functions + * Install functions. * * Do not touch those functions please * @@ -103,13 +102,13 @@ function migrateDB() $mysql = new MySQL(); $db = $mysql->connectPDO(); - $db->exec(" + $db->exec(' CREATE TABLE IF NOT EXISTS framework_migrations ( id INT AUTO_INCREMENT PRIMARY KEY, script VARCHAR(255) NOT NULL, executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); - "); + '); $sqlFiles = glob(__DIR__ . '/..//migrate/database/*.sql'); @@ -117,6 +116,7 @@ function migrateDB() usort($sqlFiles, function ($a, $b) { $aDate = intval(basename($a, '.sql')); $bDate = intval(basename($b, '.sql')); + return $aDate - $bDate; }); @@ -125,24 +125,23 @@ function migrateDB() $fileName = basename($sqlFile); - $stmt = $db->prepare("SELECT COUNT(*) FROM framework_migrations WHERE script = ?"); + $stmt = $db->prepare('SELECT COUNT(*) FROM framework_migrations WHERE script = ?'); $stmt->execute([$fileName]); $count = $stmt->fetchColumn(); if ($count == 0) { $db->exec($script); - $stmt = $db->prepare("INSERT INTO framework_migrations (script) VALUES (?)"); + $stmt = $db->prepare('INSERT INTO framework_migrations (script) VALUES (?)'); $stmt->execute([$fileName]); } else { return; } } } else { - } } catch (PDOException $e) { - die("Failed to migrate the database: " . $e->getMessage() . ""); + exit('Failed to migrate the database: ' . $e->getMessage() . ''); } } function migrateCfg() @@ -150,7 +149,7 @@ function migrateCfg() try { $mysql = new MySQL(); $db = $mysql->connectPDO(); - $db->exec("CREATE TABLE IF NOT EXISTS `framework_settings_migrations` (`id` INT NOT NULL AUTO_INCREMENT , `script` TEXT NOT NULL , `executed_at` DATETIME NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB; ALTER TABLE `framework_settings_migrations` CHANGE `executed_at` `executed_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;"); + $db->exec('CREATE TABLE IF NOT EXISTS `framework_settings_migrations` (`id` INT NOT NULL AUTO_INCREMENT , `script` TEXT NOT NULL , `executed_at` DATETIME NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB; ALTER TABLE `framework_settings_migrations` CHANGE `executed_at` `executed_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;'); $phpFiles = glob(__DIR__ . '/../migrate/config/*.php'); if (count($phpFiles) > 0) { @@ -159,29 +158,28 @@ function migrateCfg() foreach ($phpFiles as $phpFile) { $fileName = basename($phpFile); - $stmt = $db->prepare("SELECT COUNT(*) FROM framework_settings_migrations WHERE script = ?"); + $stmt = $db->prepare('SELECT COUNT(*) FROM framework_settings_migrations WHERE script = ?'); $stmt->execute([$fileName]); $count = $stmt->fetchColumn(); if ($count == 0) { include $phpFile; - $stmt = $db->prepare("INSERT INTO framework_settings_migrations (script) VALUES (?)"); + $stmt = $db->prepare('INSERT INTO framework_settings_migrations (script) VALUES (?)'); $stmt->execute([$fileName]); } } } else { - die("(CFG) No migrations found!"); + exit('(CFG) No migrations found!'); } } catch (PDOException $e) { - die("Failed to migrate the database: " . $e->getMessage() . ""); + exit('Failed to migrate the database: ' . $e->getMessage() . ''); } } - - function generateKey(): string { - $key = "mythicalcore_" . bin2hex(random_bytes(64 * 32)); + $key = 'mythicalcore_' . bin2hex(random_bytes(64 * 32)); + return $key; } diff --git a/install/mysql.php b/install/mysql.php index e0fe762..4516d13 100755 --- a/install/mysql.php +++ b/install/mysql.php @@ -4,14 +4,14 @@ ini_set('display_startup_errors', 0); error_reporting(null); if ( - isset($_GET['host']) && - !$_GET['host'] == null && - isset($_GET['port']) && - !$_GET['port'] == null && - isset($_GET['username']) && - !$_GET['username'] == null && - isset($_GET['name']) && - !$_GET['name'] == null + isset($_GET['host']) + && !$_GET['host'] == null + && isset($_GET['port']) + && !$_GET['port'] == null + && isset($_GET['username']) + && !$_GET['username'] == null + && isset($_GET['name']) + && !$_GET['name'] == null ) { $hostname = $_GET['host']; $port = (int) $_GET['port']; @@ -25,30 +25,30 @@ try { $fp = fsockopen($hostname, $port, $errCode, $errStr, $waitTimeoutInSeconds); } catch (Exception $e) { - die($e->getMessage()); + exit($e->getMessage()); } if ($fp) { $conn = new mysqli($hostname, $username, $password, $name, $port); if ($conn->connect_error) { - die($conn->connect_error); + exit($conn->connect_error); } else { echo 'OK'; } $conn->close(); } else { - die('Failed to ping: ' . $hostname . ':' . $port); + exit('Failed to ping: ' . $hostname . ':' . $port); } - die(); + exit; } else { - die('Please provide an valid ipv4/ipv6!'); + exit('Please provide an valid ipv4/ipv6!'); } } catch (Exception $e) { - die($e->getMessage()); + exit($e->getMessage()); } } else { - die('You are missing the required connection details'); + exit('You are missing the required connection details'); } function isValidIP($ip) diff --git a/lang/en_US.php b/lang/en_US.php index a6718b7..1f1eae2 100755 --- a/lang/en_US.php +++ b/lang/en_US.php @@ -1,10 +1,10 @@ "Page not found", - "pages_error_500" => "Internal server error", - "pages_error_403" => "Forbidden", - "pages_error_401" => "Unauthorized", - "pages_error_go_back" => "Go home", + // FILE: /errors/*.twig + 'pages_error_404' => 'Page not found', + 'pages_error_500' => 'Internal server error', + 'pages_error_403' => 'Forbidden', + 'pages_error_401' => 'Unauthorized', + 'pages_error_go_back' => 'Go home', ]; diff --git a/migrate/config/1.php b/migrate/config/1.php index eec82ab..34b9428 100755 --- a/migrate/config/1.php +++ b/migrate/config/1.php @@ -2,12 +2,12 @@ use MythicalSystemsFramework\Managers\SettingsManager as settings; -settings::set("app", "name", "MythicalSystems"); -settings::set("app", "logo", "https://avatars.githubusercontent.com/u/117385445"); -settings::set("app", "timezone", "Europe/Bucharest"); -settings::set("app", "theme", "default"); -settings::set("app", "lang", "en_US"); -settings::set("app", "maintenance", "false"); -settings::set("seo", "title", "MythicalSystems"); -settings::set("seo", "description", "MythicalSystems is a framework for building web applications."); -settings::set("seo", "keywords", "MythicalSystems, web applications, framework"); +settings::set('app', 'name', 'MythicalSystems'); +settings::set('app', 'logo', 'https://avatars.githubusercontent.com/u/117385445'); +settings::set('app', 'timezone', 'Europe/Bucharest'); +settings::set('app', 'theme', 'default'); +settings::set('app', 'lang', 'en_US'); +settings::set('app', 'maintenance', 'false'); +settings::set('seo', 'title', 'MythicalSystems'); +settings::set('seo', 'description', 'MythicalSystems is a framework for building web applications.'); +settings::set('seo', 'keywords', 'MythicalSystems, web applications, framework'); diff --git a/migrate/config/2.php b/migrate/config/2.php index d90cd6f..661e8b7 100755 --- a/migrate/config/2.php +++ b/migrate/config/2.php @@ -2,4 +2,4 @@ use MythicalSystemsFramework\Managers\SettingsManager as settings; -settings::set("caches", "max_query_last_time", "600"); +settings::set('caches', 'max_query_last_time', '600'); diff --git a/migrate/config/3.php b/migrate/config/3.php index 1216d0b..3775098 100755 --- a/migrate/config/3.php +++ b/migrate/config/3.php @@ -2,4 +2,4 @@ use MythicalSystemsFramework\Managers\SettingsManager as settings; -settings::set("caches", "settings_cache_life", "3600"); +settings::set('caches', 'settings_cache_life', '3600'); diff --git a/public/index.php b/public/index.php index e6f6c5b..b277935 100755 --- a/public/index.php +++ b/public/index.php @@ -1,79 +1,73 @@ composer install --no-dev --optimize-autoloader". Please run that and refresh the page'); + exit('Hello, it looks like you did not run: "composer install --no-dev --optimize-autoloader". Please run that and refresh the page'); } } catch (Exception $e) { - die('Hello, it looks like you did not run: composer install --no-dev --optimize-autoloader Please run that and refresh'); + exit('Hello, it looks like you did not run: composer install --no-dev --optimize-autoloader Please run that and refresh'); } -use MythicalSystems\Api\ResponseHandler as rsp; -use MythicalSystems\Api\Api as api; -use MythicalSystemsFramework\Database\MySQLCache; -use MythicalSystemsFramework\Managers\SettingsManager as setting; -use MythicalSystemsFramework\Managers\ConfigManager as cfg; -use MythicalSystemsFramework\Managers\LanguageManager; -use MythicalSystemsFramework\Managers\Settings; use Twig\Environment; use Twig\Loader\FilesystemLoader; +use MythicalSystems\Api\Api as api; +use MythicalSystems\Api\ResponseHandler as rsp; +use MythicalSystemsFramework\Managers\Settings; +use MythicalSystemsFramework\Managers\LanguageManager; +use MythicalSystemsFramework\Managers\ConfigManager as cfg; +use MythicalSystemsFramework\Managers\SettingsManager as setting; -$router = new \Router\Router(); - +$router = new Router\Router(); -/** +/* * Check if the app is installed */ if (file_exists(__DIR__ . '/../FIRST_INSTALL')) { $router->add('/', function () { - include(__DIR__ . '/../install/index.php'); + include __DIR__ . '/../install/index.php'; }); - $router->add('/mysql', function () { - include(__DIR__ . '/../install/mysql.php'); + include __DIR__ . '/../install/mysql.php'; }); $router->add('/install', function () { - include(__DIR__ . '/../install/install.php'); + include __DIR__ . '/../install/install.php'; }); $router->add('/(.*)', function () { header('location: /'); }); $router->route(); - die(); + exit; } - -if (cfg::get("encryption", "key") == "") { - die("We are sorry but you are missing the encryption key!"); +if (cfg::get('encryption', 'key') == '') { + exit('We are sorry but you are missing the encryption key!'); } if (!is_writable(__DIR__)) { - die("We have no access to the framework directory!"); + exit('We have no access to the framework directory!'); } if (!is_writable(__DIR__ . '/../caches')) { - die("We have no access to the cache directory!"); + exit('We have no access to the cache directory!'); } date_default_timezone_set(setting::get('app', 'timezone')); define('DIR_TEMPLATE', __DIR__ . '/../themes/' . setting::get('app', 'theme')); define('DIR_CACHE', __DIR__ . '/../caches'); define('TIMEZONE', setting::get('app', 'timezone')); -/** +/* * Load the template engine */ if (!is_dir(DIR_TEMPLATE)) { - die("The theme directory does not exist!"); + exit('The theme directory does not exist!'); } if (!is_dir(DIR_CACHE)) { @@ -83,42 +77,43 @@ $renderer = new Environment($loader, [ 'cache' => DIR_CACHE, 'auto_reload' => true, - 'debug' => true + 'debug' => true, ]); -/** +/* * Add global functions to the renderer * * This will allow the renderer to get the settings and cfg values * */ -/** +/* * Add the settings function to the renderer */ -$renderer->addFunction(new \Twig\TwigFunction('setting', function ($section, $key) { +$renderer->addFunction(new Twig\TwigFunction('setting', function ($section, $key) { return setting::get($section, $key); })); -/** +/* * Add the cfg function to the renderer */ -$renderer->addFunction(new \Twig\TwigFunction('cfg', function ($section, $key) { +$renderer->addFunction(new Twig\TwigFunction('cfg', function ($section, $key) { return cfg::get($section, $key); })); -/** +/* * Add the language function to the renderer */ -$renderer->addFunction(new \Twig\TwigFunction('lang', function ($key) { +$renderer->addFunction(new Twig\TwigFunction('lang', function ($key) { $translations = LanguageManager::getLang(); - return isset($translations[$key]) ? $translations[$key] : LanguageManager::logKeyTranslationNotFound($key); + + return $translations[$key] ?? LanguageManager::logKeyTranslationNotFound($key); })); $renderer->addGlobal('php_version', phpversion()); -$renderer->addGlobal('page_name', "Home"); +$renderer->addGlobal('page_name', 'Home'); define('VIEW_ENGINE', $renderer); /** - * Load the routes + * Load the routes. */ $routesAPIDirectory = __DIR__ . '/../routes/api/'; $iterator2 = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($routesAPIDirectory)); @@ -135,7 +130,7 @@ $router->add('/api/(.*)', function () { api::init(); - rsp::NotFound("The api route does not exist!", null); + rsp::NotFound('The api route does not exist!', null); }); $routesViewDirectory = __DIR__ . '/../routes/views/'; @@ -148,17 +143,17 @@ include $phpViewFile->getPathname(); } catch (Exception $ex) { http_response_code(500); - die('Failed to start app: ' . $ex->getMessage()); + exit('Failed to start app: ' . $ex->getMessage()); } } $router->add('/(.*)', function () { global $renderer; http_response_code(404); - die($renderer->render('/errors/404.twig')); + exit($renderer->render('/errors/404.twig')); }); try { $router->route(); } catch (Exception $e) { - die('Failed to start app: ' . $e->getMessage()); + exit('Failed to start app: ' . $e->getMessage()); } diff --git a/routes/api/system.php b/routes/api/system.php index 406e877..07abd4e 100755 --- a/routes/api/system.php +++ b/routes/api/system.php @@ -1,5 +1,5 @@ add('/api/system/logs', function () { - include(__DIR__ . '/../../api/System/logs.php'); + include __DIR__ . '/../../api/System/logs.php'; }); diff --git a/routes/views/core.php b/routes/views/core.php index cb6e4a3..468049a 100755 --- a/routes/views/core.php +++ b/routes/views/core.php @@ -1,37 +1,37 @@ add('/errors/404', function () { - /** + /* * The requirement for each template */ global $renderer; http_response_code(404); - die($renderer->render('/errors/404.twig')); + exit($renderer->render('/errors/404.twig')); }); $router->add('/errors/500', function () { - /** + /* * The requirement for each template */ global $renderer; http_response_code(500); - die($renderer->render('/errors/500.twig')); + exit($renderer->render('/errors/500.twig')); }); $router->add('/errors/403', function () { - /** + /* * The requirement for each template */ global $renderer; http_response_code(403); - die($renderer->render('/errors/403.twig')); + exit($renderer->render('/errors/403.twig')); }); $router->add('/errors/401', function () { - /** + /* * The requirement for each template */ global $renderer; http_response_code(401); - die($renderer->render('/errors/401.twig')); + exit($renderer->render('/errors/401.twig')); }); diff --git a/routes/views/index.php b/routes/views/index.php index b42c178..5bd2275 100755 --- a/routes/views/index.php +++ b/routes/views/index.php @@ -1,14 +1,10 @@ add('/', function () { - /** + /* * The requirement for each template */ global $renderer; - die($renderer->render('index.twig')); + exit($renderer->render('index.twig')); }); diff --git a/tests/EncryptionTest.php b/tests/EncryptionTest.php index 310d5e3..ee2f49e 100755 --- a/tests/EncryptionTest.php +++ b/tests/EncryptionTest.php @@ -2,29 +2,23 @@ namespace MythicalSystemsFramework\Tests; -use MythicalSystems\Utils\EncryptionHandler; use PHPUnit\Framework\TestCase; +use MythicalSystems\Utils\EncryptionHandler; class EncryptionTest extends TestCase { /** - * The encryption key - * - * @var string + * The encryption key. */ - public static string $key = "AAAAB3NzaC1yc2EAAAADAQABAAABAQDZHXFFVqeRQk42pViMsxfQhIrQBm7LcmW1sazqkgkCgoOVcW4OiCoaH0P9Zf5HjqdJ9RJocnJz8qKQQUiCFxuxt8qJiHMoqf+Mu8KgOs6ixo0SLiH2QakAZ0Nm46WB+VjXmLHkxZ9tw/f2M9dGI5Ky0M0TvsKSXS0v8crXLBBE3Fa+gao/34Cyqim1ZhCopVIjTtRNSZwx0CzHcYGhegl04+nIksCYg7RH56CTH5j1NZX8enJ7T5lx9sl8YIde6qJu7tD0nsfZFTRxwUzLvfGmFIQ9/96BNThB7aK806T8Tr+amKsPcYEc3Il6LifoPztYS6pYtbwBl3eMm0mchNgJ"; + public static string $key = 'AAAAB3NzaC1yc2EAAAADAQABAAABAQDZHXFFVqeRQk42pViMsxfQhIrQBm7LcmW1sazqkgkCgoOVcW4OiCoaH0P9Zf5HjqdJ9RJocnJz8qKQQUiCFxuxt8qJiHMoqf+Mu8KgOs6ixo0SLiH2QakAZ0Nm46WB+VjXmLHkxZ9tw/f2M9dGI5Ky0M0TvsKSXS0v8crXLBBE3Fa+gao/34Cyqim1ZhCopVIjTtRNSZwx0CzHcYGhegl04+nIksCYg7RH56CTH5j1NZX8enJ7T5lx9sl8YIde6qJu7tD0nsfZFTRxwUzLvfGmFIQ9/96BNThB7aK806T8Tr+amKsPcYEc3Il6LifoPztYS6pYtbwBl3eMm0mchNgJ'; /** - * The data to encrypt - * - * @var string + * The data to encrypt. */ - public static string $data = "Hello World, this is a unit test for the encryption handler :)!"; + public static string $data = 'Hello World, this is a unit test for the encryption handler :)!'; /** - * The encrypted data - * - * @var string + * The encrypted data. */ - public static string $data_e = "iaatrbFTpenTr5Wlg6atqrRhqrdhsmG3r6q1YrW2t85ovrW4duXNt3HQopXiz9nB3OfUcdCq4LWu0qlsnZZ4"; + public static string $data_e = 'iaatrbFTpenTr5Wlg6atqrRhqrdhsmG3r6q1YrW2t85ovrW4duXNt3HQopXiz9nB3OfUcdCq4LWu0qlsnZZ4'; public function testDecryption(): void { @@ -37,5 +31,4 @@ public function testEncryption(): void $encryptedData = EncryptionHandler::encrypt(self::$data, self::$key); $this->assertEquals(self::$data_e, $encryptedData); } - }