From 609ed2e287aea926f0e2a25725ae3666012aa744 Mon Sep 17 00:00:00 2001 From: Juan Cristobal <65052633+juancristobalgd1@users.noreply.github.com> Date: Fri, 21 Jun 2024 09:41:56 +0200 Subject: [PATCH] update file --- src/App.php | 29 ++- src/Controller.php | 12 +- src/autoload.php | 24 ++- src/functions.php | 121 +++++-------- src/libraries/Auth/Auth.php | 50 +----- src/libraries/Cache/Cache.php | 16 -- src/libraries/Cache/Drivers/FileCache.php | 66 +++---- .../Cache/Drivers/MemcachedCache.php | 39 +--- src/libraries/Cache/Drivers/RedisCache.php | 51 +----- src/libraries/Cache/InterfaceCache.php | 32 +--- src/libraries/Console/BaseCommand.php | 30 +--- src/libraries/Console/GeneratorTrait.php | 167 +++++++----------- src/libraries/Console/HelpConsole.php | 38 ++-- src/libraries/Encryption/Encrypter.php | 12 -- src/libraries/Http/CacheTrait.php | 7 - src/libraries/Http/Curl.php | 27 +-- src/libraries/Http/OAuthTrait.php | 6 - src/libraries/Http/Promise.php | 35 +--- src/libraries/Http/ProxyTrait.php | 8 - src/libraries/Http/Request.php | 23 ++- src/libraries/Http/URI.php | 42 +---- src/libraries/Lang/Lang.php | 14 -- src/libraries/Middlewares/AuthMiddleware.php | 8 - .../Middlewares/MaintenanceMiddleware.php | 15 +- src/libraries/Session/Session.php | 91 +--------- 25 files changed, 251 insertions(+), 712 deletions(-) diff --git a/src/App.php b/src/App.php index 3415020..70bf61c 100644 --- a/src/App.php +++ b/src/App.php @@ -76,21 +76,20 @@ private function loadEnv(): void */ private function configureEnvironment(): void { - static $initialized = false; - if (!$initialized) { - - $environment = Env::get('APP_ENVIRONMENT', 'production'); - if ($environment === 'debug') { - ini_set('display_errors', 1); - error_reporting(E_ALL); - } else { - error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED - & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED); - ini_set('display_errors', 0); - } - - $initialized = true; - } + static $isInitialized = false; + + if ($isInitialized) + return; + + $environment = Env::get('APP_ENVIRONMENT', 'production'); + $isInDebugMode = $environment === 'debug'; + + error_reporting( + $isInDebugMode ? E_ALL : (E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED) + ); + ini_set('display_errors', $isInDebugMode ? 1 : 0); + + $isInitialized = true; } /** diff --git a/src/Controller.php b/src/Controller.php index 851bc64..dfb0a70 100644 --- a/src/Controller.php +++ b/src/Controller.php @@ -59,9 +59,9 @@ class Controller public function __construct() { $app = app(); - $this->request = $app->request; + $this->request = $app->request; $this->response = $app->response; - $this->view = $app->view; + $this->view = $app->view; $this->registerDefaultMiddleware(); } @@ -122,9 +122,13 @@ public function getAction(): string /** * Render the view. */ - public function renderView(string $view, string|array $params = null, bool $withLayout = true, string $ext = '.php'): ?string + public function renderView(string $viewName, $viewData = null, bool $withLayout = true, string $fileExtension = '.php'): ?string { - return $this->view->render($view, $ext)->withData($params)->withLayout($withLayout)->get(); + return $this->view + ->withData($viewData) + ->withLayout($withLayout) + ->render($viewName, $fileExtension) + ->get(); } /** diff --git a/src/autoload.php b/src/autoload.php index b8cecde..2042ae2 100644 --- a/src/autoload.php +++ b/src/autoload.php @@ -12,18 +12,16 @@ function axm_autoloader(string $class) { - static $classMap; - - $classMap ??= [ - - 'Axm' => AXM_PATH . DIRECTORY_SEPARATOR . 'Axm.php', - 'Container' => AXM_PATH . DIRECTORY_SEPARATOR . 'Container.php', - 'App' => AXM_PATH . DIRECTORY_SEPARATOR . 'App.php', - 'Config' => AXM_PATH . DIRECTORY_SEPARATOR . 'Config.php', - 'Env' => AXM_PATH . DIRECTORY_SEPARATOR . 'Env.php', - 'Facade' => AXM_PATH . DIRECTORY_SEPARATOR . 'Facade.php', - 'Controller' => AXM_PATH . DIRECTORY_SEPARATOR . 'Controller.php', - 'BaseModel' => AXM_PATH . DIRECTORY_SEPARATOR . 'BaseModel.php', + static $classMap = [ + + 'Axm' => AXM_PATH . DIRECTORY_SEPARATOR . 'Axm.php', + 'Container' => AXM_PATH . DIRECTORY_SEPARATOR . 'Container.php', + 'App' => AXM_PATH . DIRECTORY_SEPARATOR . 'App.php', + 'Config' => AXM_PATH . DIRECTORY_SEPARATOR . 'Config.php', + 'Env' => AXM_PATH . DIRECTORY_SEPARATOR . 'Env.php', + 'Facade' => AXM_PATH . DIRECTORY_SEPARATOR . 'Facade.php', + 'Controller' => AXM_PATH . DIRECTORY_SEPARATOR . 'Controller.php', + 'BaseModel' => AXM_PATH . DIRECTORY_SEPARATOR . 'BaseModel.php', ]; if (isset($classMap[$class])) { @@ -43,4 +41,4 @@ function axm_autoloader(string $class) } -spl_autoload_register('axm_autoloader'); +spl_autoload_register('axm_autoloader'); \ No newline at end of file diff --git a/src/functions.php b/src/functions.php index 8626402..5a873ac 100644 --- a/src/functions.php +++ b/src/functions.php @@ -30,21 +30,21 @@ function config(string $key = null, mixed $value = null) if (!function_exists('app')) { /** - * Return the Axm instance + * Returns the Axm instance or a value from the instance by alias. */ - function app(?string $alias = null, $value = null): object + function app(string $alias = null, mixed $value = null): object { - $instance = Axm::getApp(); + $axmInstance = Axm::getApp(); if (null === $alias) { - return $instance; + return $axmInstance; } if (null !== $value) { - return $instance->$alias = $value; + $axmInstance->$alias = $value; } - return $instance->$alias; + return $axmInstance->$alias; } } @@ -87,9 +87,9 @@ function extend(string $layout) function view(string $view, string|array $params = null, bool $show = false, bool $withLayout = false, string $ext = '.php'): ?string { return app('view', new View) - ->render($view, $ext) ->withData($params) ->withLayout($withLayout) + ->render($view, $ext) ->get(); } } @@ -392,13 +392,12 @@ function isLogged(): bool if (!function_exists('old')) { /** - * Used to show again if the data sent in - * html elements (input, select, textarea, etc) sent by the POST method exist. - * e.g.: old('name); **/ - function old(string $value): string + * Returns the previously submitted value of a form field with the given name, if it exists. + */ + function old(string $fieldName): string { - $input = app()->request->post(); - return (isset($input[$value]) && !empty($input[$value])) ? $input[$value] : ''; + $submittedValues = app()->request->post(); + return $submittedValues[$fieldName] ?? ''; } } @@ -452,22 +451,15 @@ function now() /** * Create a new string helper instance or operate on a string. - * @return Stringable|object Returns a Stringable instance if a string argument is provided. */ - function str(?string $string = null) + function str(?string $string = null): Stringable { - if (is_null($string)) { - // Return a new class instance for chaining string methods - return new class { - public function __call($method, $params) - { - // Delegate method calls to the Str class - return Str::$method(...$params); - } - }; - } - // Return a Stringable instance for the provided string - return Str::of($string); + return is_null($string) ? new class { + public function __call(string $method, array $arguments) + { + return Str::$method(...$arguments); + } + } : Str::of($string); } } @@ -498,64 +490,41 @@ function to_object(array &$array): stdClass } } -/** - * Load one or multiple helpers. - */ -function helpers($helpers, ?string $customPath = null, string $separator = '_'): bool -{ - return (new class ($helpers, $customPath, $separator) { - private $helpers; - private $customPath; - private $separator; - - public function __construct($helpers, ?string $customPath, string $separator) - { - $this->helpers = $this->normalizeHelpers($helpers); - $this->customPath = $customPath ? rtrim($customPath, DIRECTORY_SEPARATOR) : null; - $this->separator = $separator; - } - - private function normalizeHelpers($helpers): array - { - if (is_string($helpers)) { - return preg_split('/[\s,\.]+/', $helpers); - } elseif (!is_array($helpers)) { - throw new InvalidArgumentException('The $helpers variable must be an array.'); - } - - return $helpers; - } +if (!function_exists('helpers')) { - public function __invoke(): bool - { - $config = config('paths'); - $appPath = $config['helpersPath']; - $axmHelpersPath = $config['helpersAxmPath']; + /** + * Load one or multiple helpers. + */ + function helpers($helpers, ?string $customPath = null, string $separator = '_'): bool + { + $helpers = is_string($helpers) ? preg_split('/[\s,\.]+/', $helpers) : $helpers; + $customPath = $customPath ? rtrim($customPath, DIRECTORY_SEPARATOR) : null; - foreach ($this->helpers as $helper) { - $helper = trim($helper) . $this->separator . 'helper.php'; + $config = config('paths'); + $appHelpersPath = $config['helpersPath']; + $axmHelpersPath = $config['helpersAxmPath']; - if ($this->customPath && is_file($customHelperFile = $this->customPath . DIRECTORY_SEPARATOR . $helper)) { - require_once $customHelperFile; - continue; - } + foreach ($helpers as $helper) { + $helperFile = "$helper$separator" . 'helper.php'; - if (is_file($appHelperFile = $appPath . DIRECTORY_SEPARATOR . $helper)) { - require_once $appHelperFile; - continue; - } + if ($customPath && is_file($customPath . DIRECTORY_SEPARATOR . $helperFile)) { + require_once "$customPath/$helperFile"; + continue; + } - if (is_file($axmHelperFile = $axmHelpersPath . DIRECTORY_SEPARATOR . $helper)) { - require_once $axmHelperFile; - continue; + $paths = [$appHelpersPath, $axmHelpersPath]; + foreach ($paths as $path) { + if (is_file("$path/$helperFile")) { + require_once "$path/$helperFile"; + continue 2; } - - throw new Exception("The helper '$axmHelperFile' does not exist in any of the specified paths."); } - return true; + throw new Exception("The helper '$helperFile' does not exist in any of the specified paths."); } - })(); + + return true; + } } if (!function_exists('getRouteParams')) { diff --git a/src/libraries/Auth/Auth.php b/src/libraries/Auth/Auth.php index 5eb1251..67be1f5 100644 --- a/src/libraries/Auth/Auth.php +++ b/src/libraries/Auth/Auth.php @@ -32,11 +32,6 @@ class Auth /** * __construct - * - * @param App $app - * @param string $usernameField - * @param string $passwordField - * @return void */ public function __construct(App $app, string $usernameField = 'email', string $passwordField = 'password') { @@ -50,10 +45,6 @@ public function __construct(App $app, string $usernameField = 'email', string $p /** * Attempts to log in a user based on provided data. - * - * @param array[] ...$keyValuePairs An array or nested arrays containing the fields and values to use for the database query. - * @return bool Returns true if the login is successful, false otherwise. - * @throws \Exception Throws an exception in case of an error during the login process. */ public function resolverLogin(array ...$keyValuePairs): bool { @@ -67,10 +58,6 @@ public function resolverLogin(array ...$keyValuePairs): bool /** * Attempts to log in a user based on a single key-value pair. - * - * @param array $data An associative array containing user login data. - * @return bool Returns true if the login is successful, false otherwise. - * @throws \Exception Throws an exception in case of an error during the login process. */ private function loginWithSingleKey(array $data): bool { @@ -86,11 +73,6 @@ private function loginWithSingleKey(array $data): bool /** * Attempts to log in a user based on multiple key-value pairs. - * - * @param array $keys An array containing the fields to use for the database query. - * @param array $values An array containing the corresponding values to match in the database query. - * @return bool Returns true if the login is successful, false otherwise. - * @throws \Exception Throws an exception in case of an error during the login process. */ private function loginWithMultipleKeys(array $keys, array $values): bool { @@ -110,10 +92,6 @@ private function loginWithMultipleKeys(array $keys, array $values): bool /** * Sets the user session based on the provided user ID and data. - * - * @param string $userId The key to use for storing user data in the session. - * @param mixed $result The user data to store in the session. - * @return bool */ private function setUserSession($userId, $result): bool { @@ -122,11 +100,6 @@ private function setUserSession($userId, $result): bool /** * Retrieves a user from the database based on provided field and value. - * - * @param string $userClass The class representing the user model. - * @param string $field The field to use for the database query. - * @param mixed $value The value to match in the database query. - * @return mixed|null Returns the user object if found, or null if no user is found. */ private function getUserFromDatabase(string $userClass, string $field, $value) { @@ -135,35 +108,28 @@ private function getUserFromDatabase(string $userClass, string $field, $value) } /** - * Performs a login attempt with the provided credentials - * Returns true if the login was successful, false otherwise. - * - * @param mixed $username - * @param mixed $password - * @return bool + * Attempts a login with the given credentials. */ - public function attempt(string $username, string $password) + public function attemptLogin(string $username, string $password): bool { if ($this->failedAttempts >= $this->maxFailedAttempts) { - throw new Exception('You have reached the maximum number of failed attempts.'); + throw new Exception('Maximum number of failed login attempts reached.'); } - $this->userModel = $this->getUserFromDatabase($this->userClass, $this->usernameField, $username); + $user = $this->getUserFromDatabase($this->userClass, $this->usernameField, $username); - if (!$this->userModel || !password_verify($password, $this->userModel->{$this->passwordField})) { - ++$this->failedAttempts; + if (!$user || !password_verify($password, $user->{$this->passwordField})) { + $this->failedAttempts++; return false; } $this->failedAttempts = 0; - $this->session->write($this->userId, $this->userModel->{$this->userModel->primaryKey}); + $this->session->write($this->userId, $user->{$this->userModel->getKeyName()}); return true; } /** * Checks if there is a currently authenticated user - * Returns true if there is an authenticated user, false otherwise. - * @return bool */ public function check(): bool { @@ -173,7 +139,6 @@ public function check(): bool /** * Returns the currently authenticated user or null if there * is no authenticated user. - * @return void */ public function user() { @@ -184,7 +149,6 @@ public function user() /** * Logs out the current user. - * @return void */ public function logout(string $path = null): void { diff --git a/src/libraries/Cache/Cache.php b/src/libraries/Cache/Cache.php index 1dbc743..d9a630f 100644 --- a/src/libraries/Cache/Cache.php +++ b/src/libraries/Cache/Cache.php @@ -21,46 +21,36 @@ abstract class Cache implements InterfaceCache /** * Default cache driver name. - * @var string */ protected static string $defaultDriver = 'File'; /** * Namespace for cache driver classes. - * @var string */ protected static string $namespace = 'Axm\\Cache\\Drivers\\'; /** * Unique identifier for the cache instance. - * @var string */ protected string $id; /** * Cache group identifier. - * @var string */ protected string $group = 'default'; /** * Cache lifetime. - * @var string */ protected string $lifetime = ''; /** * Array to store starting times for profiling. - * @var array */ protected array $start = []; /** * Retrieves or initializes a cache driver instance. - * - * @param string|null $driver Optional. The name of the cache driver. - * Defaults to the default driver. - * @return InterfaceCache The cache driver instance. */ public static function driver(string $driver = null): InterfaceCache { @@ -73,9 +63,6 @@ public static function driver(string $driver = null): InterfaceCache /** * Resolves and instantiates a cache driver if not already initialized. - * - * @param string $driver The name of the cache driver. - * @return void */ protected static function resolveDriver(string $driver = 'File'): void { @@ -88,9 +75,6 @@ protected static function resolveDriver(string $driver = 'File'): void /** * Sets the default cache driver. - * - * @param string $driver The name of the default cache driver. - * @return void */ public static function setDefaultDriver(string $driver = 'File'): void { diff --git a/src/libraries/Cache/Drivers/FileCache.php b/src/libraries/Cache/Drivers/FileCache.php index a75f64e..17aad45 100644 --- a/src/libraries/Cache/Drivers/FileCache.php +++ b/src/libraries/Cache/Drivers/FileCache.php @@ -8,7 +8,7 @@ /** * FileCache is a caching driver that stores cache data in files. * - * @package Axm\Cache\Drivers + * @package Cache\Drivers */ class FileCache extends Cache { @@ -18,58 +18,55 @@ class FileCache extends Cache public const DEFAULT_EXPIRE = 31536000; // 1 year /** - * @var string|null The path to the cache directory. + * The path to the cache directory. */ - public $cachePath; + public ?string $cachePath; /** - * @var int The permission for creating the cache directory. + * The permission for creating the cache directory. */ - public $cachePathPermission = self::DEFAULT_CACHE_PATH_PERMISSION; + public int $cachePathPermission = self::DEFAULT_CACHE_PATH_PERMISSION; /** - * @var string The suffix for cache file names. + * The suffix for cache file names. */ - public $cacheFileSuffix = self::DEFAULT_CACHE_FILE_SUFFIX; + public string $cacheFileSuffix = self::DEFAULT_CACHE_FILE_SUFFIX; /** - * @var int The permission for creating cache files. + * The permission for creating cache files. */ - public $cacheFilePermission = self::DEFAULT_CACHE_FILE_PERMISSION; + public int $cacheFilePermission = self::DEFAULT_CACHE_FILE_PERMISSION; /** - * @var int The number of directory levels to create within the cache directory. + * The number of directory levels to create within the cache directory. */ - public $directoryLevels = 0; + public int $directoryLevels = 0; /** - * @var bool Whether to embed expiry information in the cache file. + * Whether to embed expiry information in the cache file. */ - public $embedExpiry = false; + public bool $embedExpiry = false; /** - * @var int The default expiration time for cache items (1 year by default). + * The default expiration time for cache items (1 year by default). */ - public $expire = self::DEFAULT_EXPIRE; + public int $expire = self::DEFAULT_EXPIRE; /** - * @var int The garbage collection probability (default is 100). - * Higher values increase the likelihood of garbage collection. + * The garbage collection probability (default is 100). */ - private $_gcProbability = 100; + private int $_gcProbability = 100; /** - * @var bool Internal flag to track whether garbage collection has been performed. + * Internal flag to track whether garbage collection has been performed. */ - private $_gced = false; + private bool $_gced = false; /** * Initializes the cache component. * * If the cache path is not set, it defaults to the 'cacheViewPath' configuration. * If the cache directory doesn't exist, it will be created with the specified permission. - * - * @throws RuntimeException If the cache path is not writable. */ public function init(): void { @@ -86,7 +83,6 @@ public function init(): void /** * Clears all cached data. - * @return bool Whether the operation was successful. */ public function flush(): bool { @@ -96,11 +92,8 @@ public function flush(): bool /** * Retrieves a cached value based on a given key. - * - * @param string $key The key for the cached value. - * @return mixed|false The cached value if found, or false if not found or expired. */ - public function get(string $key) + public function get(string $key): false|string|int|array|object|null { $cacheFile = $this->getCacheFile($key); if (file_exists($cacheFile) && !$this->isExpired($cacheFile)) { @@ -115,11 +108,6 @@ public function get(string $key) /** * Stores a value in the cache with a specified key and optional expiration time. - * - * @param string $key The key for the cached value. - * @param mixed $value The value to be cached. - * @param int $expire The expiration time for the cache entry in seconds. - * @return bool Whether the operation was successful. */ public function set(string $key, $value, int $expire = 0): bool { @@ -139,9 +127,6 @@ public function set(string $key, $value, int $expire = 0): bool /** * Deletes a cached value based on a given key. - * - * @param string $key The key for the cached value. - * @return bool Whether the operation was successful. */ public function delete(string $key): bool { @@ -151,9 +136,6 @@ public function delete(string $key): bool /** * Gets the absolute path to the cache file for a given key. - * - * @param string $key The key for the cached value. - * @return string The absolute path to the cache file. */ private function getCacheFile(string $key): string { @@ -171,7 +153,6 @@ private function getCacheFile(string $key): string /** * Performs garbage collection on expired cache files. - * @param bool $expiredOnly If true, only expired files will be deleted. */ private function gc(bool $expiredOnly = true): void { @@ -193,7 +174,6 @@ private function gc(bool $expiredOnly = true): void /** * Gets the garbage collection (GC) probability. - * @return int The GC probability. */ private function getGCProbability(): int { @@ -202,7 +182,6 @@ private function getGCProbability(): int /** * Sets the garbage collection (GC) probability. - * @param int $value The GC probability to set, clamped between 0 and 1,000,000. */ private function setGCProbability(int $value): void { @@ -211,9 +190,6 @@ private function setGCProbability(int $value): void /** * Checks whether a cached file has expired. - * - * @param string $cacheFile The absolute path to the cache file. - * @return bool Whether the cache file has expired. */ private function isExpired(string $cacheFile): bool { @@ -230,7 +206,6 @@ private function isExpired(string $cacheFile): bool /** * Gets the default expiration time for cache files. - * @return int The default expiration time in seconds. */ public function getExpire(): int { @@ -239,7 +214,6 @@ public function getExpire(): int /** * Gets all cache files in the cache directory. - * @return array An array of cache file paths. */ public function getAllFiles(): array { diff --git a/src/libraries/Cache/Drivers/MemcachedCache.php b/src/libraries/Cache/Drivers/MemcachedCache.php index b9f25eb..e8057b7 100644 --- a/src/libraries/Cache/Drivers/MemcachedCache.php +++ b/src/libraries/Cache/Drivers/MemcachedCache.php @@ -14,14 +14,14 @@ class MemcachedCache extends Cache { /** - * @var Memcached The Memcached instance. + * The Memcached instance. */ - protected $memcached; + protected Memcached $memcached; /** - * @var array Memcached server configurations. + * Memcached server configurations. */ - protected $servers = [ + protected array $servers = [ [ 'host' => 'localhost', 'port' => 11211, @@ -34,8 +34,6 @@ class MemcachedCache extends Cache /** * Initializes the connection to Memcached. - * - * @throws \Exception If failed to connect to Memcached. */ public function init() { @@ -54,19 +52,14 @@ public function init() ); } } catch (\Exception $e) { - // Handle the Memcached connection exception as needed throw new \Exception('Failed to connect to Memcached: ' . $e->getMessage()); } } /** * Gets a value from Memcached for the given key. - * - * @param string $key The key to retrieve the value. - * @return mixed|null The stored value or null if not found. - * @throws \RuntimeException If an error occurs during the operation with Memcached. */ - public function get($key) + public function get(string $key): false|string|int|array|object|null { try { $value = $this->memcached->get($key); @@ -80,14 +73,8 @@ public function get($key) /** * Stores a value in Memcached with the given key. - * - * @param string $key The key to store the value. - * @param mixed $value The value to store. - * @param int $expire The expiration time in seconds (0 for never expire). - * @return bool True if stored successfully, false otherwise. - * @throws \RuntimeException If an error occurs during the operation with Memcached. */ - public function set($key, $value, $expire = 0) + public function set(string $key, mixed $value, int $expire = 0): bool { try { // Automatically serialize objects @@ -95,40 +82,30 @@ public function set($key, $value, $expire = 0) return $this->memcached->set($key, $serializedValue, $expire); } catch (\Exception $e) { - // Handle the Memcached operation exception as needed throw new RuntimeException('Error setting value in Memcached: ' . $e->getMessage()); } } /** * Deletes a value from Memcached with the given key. - * - * @param string $key The key of the value to be deleted. - * @return bool True if deleted successfully, false otherwise. - * @throws \RuntimeException If an error occurs during the operation with Memcached. */ - public function delete($key) + public function delete(string $key): bool { try { return $this->memcached->delete($key); } catch (\Exception $e) { - // Handle the Memcached operation exception as needed throw new RuntimeException('Error deleting value from Memcached: ' . $e->getMessage()); } } /** * Flushes all values from Memcached. - * - * @return bool True if the flush operation was successful, false otherwise. - * @throws \RuntimeException If an error occurs during the operation with Memcached. */ - public function flush() + public function flush(): bool { try { return $this->memcached->flush(); } catch (\Exception $e) { - // Handle the Memcached operation exception as needed throw new \Exception('Error flushing Memcached cache: ' . $e->getMessage()); } } diff --git a/src/libraries/Cache/Drivers/RedisCache.php b/src/libraries/Cache/Drivers/RedisCache.php index 8ad1251..f84479e 100644 --- a/src/libraries/Cache/Drivers/RedisCache.php +++ b/src/libraries/Cache/Drivers/RedisCache.php @@ -12,28 +12,27 @@ /** * RedisCache - Implementation of the class for handling cache with Redis. - * - * @package Axm\Cache\Drivers + * @package Cache\Drivers */ class RedisCache extends Cache { /** - * @var Redis|RedisCluster Redis client instance. + * Redis client instance. */ protected $redis; /** - * @var bool Indicates whether Redis is configured as a cluster. + * Indicates whether Redis is configured as a cluster. */ - protected $cluster; + protected bool $cluster; /** - * @var array Redis connection options. + * Redis connection options. */ - protected $options = [ + protected array $options = [ 'scheme' => 'tcp', - 'host' => '127.0.0.1', - 'port' => 6379, + 'host' => '127.0.0.1', + 'port' => 6379, 'timeout' => 2.5, 'read_timeout' => 2.5, ]; @@ -62,19 +61,14 @@ public function init() ); } } catch (RedisException $e) { - // Handle the Redis connection exception as needed throw new \Exception('Failed to connect to Redis: ' . $e->getMessage()); } } /** * Gets the value associated with a key from Redis. - * - * @param string $key The key to look up in Redis. - * @return mixed The value associated with the key, or null if not found. - * @throws RuntimeException If an error occurs while getting the value. */ - public function get(string $key) + public function get(string $key): false|string|int|array|object|null { try { return $this->redis->get($key); @@ -85,12 +79,6 @@ public function get(string $key) /** * Sets a value identified by a key into Redis. - * - * @param string $key The key identifying the value to be cached. - * @param mixed $value The value to be cached. - * @param int $expire The number of seconds until the cached value will expire. 0 means never expire. - * @return bool True if the value is successfully stored in Redis, false otherwise. - * @throws RuntimeException If an error occurs while setting the value. */ public function set(string $key, $value, int $expire = 0): bool { @@ -101,33 +89,24 @@ public function set(string $key, $value, int $expire = 0): bool return $this->redis->set($key, $value); } } catch (RedisException $e) { - // Handle the Redis operation exception as needed throw new RuntimeException('Error setting value in Redis: ' . $e->getMessage()); } } /** * Deletes a value with the specified key from Redis. - * - * @param string $key The key of the value to be deleted. - * @return bool True if the value is successfully deleted, false otherwise. - * @throws RuntimeException If an error occurs while deleting the value. */ public function delete(string $key): bool { try { return $this->redis->del($key) > 0; } catch (RedisException $e) { - // Handle the Redis operation exception as needed throw new RuntimeException('Error deleting value from Redis: ' . $e->getMessage()); } } /** * Flushes all values from Redis cache. - * - * @return bool True if the flush operation was successful, false otherwise. - * @throws \Exception If an error occurs while flushing the cache. */ public function flush(): bool { @@ -138,42 +117,30 @@ public function flush(): bool return $this->redis->flushDB(); } } catch (RedisException $e) { - // Handle the Redis operation exception as needed throw new \Exception('Error flushing Redis cache: ' . $e->getMessage()); } } /** * Sets the expiration time for a key in Redis. - * - * @param string $key The key for which to set the expiration time. - * @param int $expire The number of seconds until the key will expire. - * @return bool True if the expiration time is set successfully, false otherwise. - * @throws \Exception If an error occurs while setting the expiration time. */ public function expire(string $key, int $expire): bool { try { return $this->redis->expire($key, $expire); } catch (RedisException $e) { - // Handle the Redis operation exception as needed throw new \Exception('Error setting expiration for key in Redis: ' . $e->getMessage()); } } /** * Gets multiple values from Redis with the specified keys. - * - * @param array $keys A list of keys identifying the cached values. - * @return array A list of cached values indexed by the keys. - * @throws \Exception If an error occurs while getting multiple values. */ public function mget(array $keys): array { try { return $this->redis->mget($keys); } catch (RedisException $e) { - // Handle the Redis operation exception as needed throw new \Exception('Error getting multiple values from Redis: ' . $e->getMessage()); } } diff --git a/src/libraries/Cache/InterfaceCache.php b/src/libraries/Cache/InterfaceCache.php index b994445..05fa7ca 100644 --- a/src/libraries/Cache/InterfaceCache.php +++ b/src/libraries/Cache/InterfaceCache.php @@ -9,39 +9,19 @@ */ interface InterfaceCache { + /** - * Retrieves a value from cache with a specified key. - * - * @param string $key A key identifying the cached value. - * @return mixed|false The value stored in the cache, false if the value is not in the cache or expired. + * Retrieves a value from cache associated with the given key. */ - public function get(string $key); + public function get(string $key): false|string|int|array|object|null; /** * Stores a value identified by a key into cache. - * - * If the cache already contains such a key, the existing value and - * expiration time will be replaced with the new ones. - * @param string $key The key identifying the value to be cached. - * @param mixed $value The value to be cached. - * @param int $expire The number of seconds in which the cached value will expire. 0 means never expire. - * @return bool True if the value is successfully stored into the cache, false otherwise. */ - public function set(string $key, $value, int $expire = 0); + public function set(string $key, mixed $value, int $expire = 0): bool; /** * Deletes a value with the specified key from cache. - * - * @param string $key The key of the value to be deleted. - * @return bool Whether the deletion is successful. - */ - public function delete(string $key); - - /** - * Deletes all values from cache. - * - * Be careful when performing this operation if the cache is shared by multiple applications. - * @return bool Whether the flush operation was successful. */ - public function flush(); -} + public function delete(string $key): bool; +} \ No newline at end of file diff --git a/src/libraries/Console/BaseCommand.php b/src/libraries/Console/BaseCommand.php index 72eeba6..a79007c 100644 --- a/src/libraries/Console/BaseCommand.php +++ b/src/libraries/Console/BaseCommand.php @@ -17,7 +17,6 @@ use Console\CLI; use Console\Commands; use Psr\Log\LoggerInterface; -use ReflectionException; /** @@ -37,37 +36,31 @@ abstract class BaseCommand /** * The group the command is lumped under * when listing commands. - * @var string */ protected string $group; /** * The Command's name - * @var string */ protected string $name; /** * the Command's usage description - * @var string */ protected string $usage; /** * the Command's short description - * @var string */ protected string $description; /** * the Command's options description - * @var array */ protected array $options = []; /** * the Command's Arguments description - * @var array */ protected array $arguments = []; @@ -78,9 +71,6 @@ abstract class BaseCommand */ protected $commands = []; - /** - * @var array - */ private array $params = []; protected const ARROW_SYMBOL = '➜ '; @@ -88,13 +78,11 @@ abstract class BaseCommand /** * Actually execute a command. - * @param array $params */ abstract public function run(array $params); /** * Define a protected method commands that returns a new instance of the Commands class - * if it hasn't been set yet */ protected function commands() { @@ -107,9 +95,6 @@ protected function commands() /** * Can be used by a command to run other commands. - * - * @throws ReflectionException - * @return mixed */ protected function call(string $command, array $params = []) { @@ -123,14 +108,10 @@ public function showHelp() { CLI::write('CLI help Usage: ', 'yellow'); - if (!empty ($this->usage)) { - $usage = $this->usage; - } else { - $usage = $this->name; + $usage = $this->usage ?? $this->name; - if (!empty ($this->arguments)) { - $usage .= ' [arguments]'; - } + if (!empty ($this->arguments)) { + $usage .= ' [arguments]'; } CLI::write($this->setPad($usage, 0, 0, 2)); @@ -166,7 +147,6 @@ public function showHelp() /** * Pads our string out so that all titles are the same length to nicely line up descriptions. - * @param int $extra How many extra spaces to add at the end */ public function setPad(string $item, int $max, int $extra = 2, int $indent = 0): string { @@ -176,9 +156,6 @@ public function setPad(string $item, int $max, int $extra = 2, int $indent = 0): /** * Get pad for $key => $value array output - * - * @deprecated Use setPad() instead. - * @codeCoverageIgnore */ public function getPad(array $array, int $pad): int { @@ -192,7 +169,6 @@ public function getPad(array $array, int $pad): int /** * Makes it simple to access our protected properties. - * @return mixed */ public function __get(string $key) { diff --git a/src/libraries/Console/GeneratorTrait.php b/src/libraries/Console/GeneratorTrait.php index cb1307f..7a5126b 100644 --- a/src/libraries/Console/GeneratorTrait.php +++ b/src/libraries/Console/GeneratorTrait.php @@ -22,80 +22,67 @@ trait GeneratorTrait { /** * Component Name - * @var string */ - protected $component; + protected string $component; /** * File directory - * @var string */ - protected $directory; + protected string $directory; /** * View template name - * @var string */ - protected $template; + protected string $template; /** * namespace the class */ - protected $namespace; + protected string $namespace; /** * Language string key for required class names. - * @var string */ - protected $classNameLang = ''; + protected string $classNameLang = ''; /** * class names. - * @var string */ - protected $className; + protected string $className; /** * Whether to require class name. - * * @internal - * @var bool */ - private $hasClassName = true; + private bool $hasClassName = true; /** * Whether to sort class imports. - * * @internal - * @var bool */ - private $sortImports = true; + private bool $sortImports = true; /** * Whether the `--suffix` option has any effect. - * * @internal - * @var bool */ - private $enabledSuffixing = true; + private bool $enabledSuffixing = true; /** * The params array for easy access by other methods. - * * @internal - * @var array */ - private $params = []; + private array $params = []; /** * Data passed to templates */ - protected $data = []; + protected array $data = []; /** * Data passed to templates */ - protected $replace = []; + protected array $replace = []; protected bool $phpOutputOnly = true; @@ -107,67 +94,71 @@ trait GeneratorTrait protected function execute(array $params): void { $this->params = $params; - if ($this->getOption('namespace') === 'Axm') { - CLI::write(self::ARROW_SYMBOL . 'CLI generator using [ Axm ] Namespace. ⚠ ', 'yellow'); - CLI::newLine(); + $namespace = $this->getOption('namespace'); + $isAxmNamespace = $namespace === 'Axm'; - if (CLI::prompt(self::ARROW_SYMBOL . 'Are you sure you want to continue? ❓ ', ['y', 'n'], 'required') === 'n') { - CLI::newLine(); - CLI::write(self::ARROW_SYMBOL . 'CLI generator cancel Operation ', 'yellow'); - CLI::newLine(); - return; - } - - CLI::newLine(); + if ($isAxmNamespace) { + $this->promptUserToContinue($namespace); } - // Get the fully qualified class name from the input. $class = $this->qualifyClassName(); + $path = $this->buildPath($class); - // Get the file path from class name. - $path = $this->buildPath($this->className ?? $class); - - // Check if path is empty. if (empty($path)) { return; } - $isFile = is_file($path); + $isFile = file_exists($path); - // Overwriting files unknowingly is a serious annoyance, So we'll check if - // we are duplicating things, If 'force' option is not supplied, we bail. if (!$this->getOption('force') && $isFile) { CLI::error(self::ARROW_SYMBOL . 'File exist: ' . realpath($path) . ' ❌ ', 'light_gray'); - CLI::newLine(); return; } - // Check if the directory to save the file is existing. - $dir = dirname($path); - if (!is_dir($dir)) { - mkdir($dir, 0755, true); - } - - helpers('filesystem'); + $this->createDirectory(dirname($path)); - // Build the class based on the details we have, We'll be getting our file - // contents from the template, and then we'll do the necessary replacements. - if (!writeFile($path, $this->buildContent($class, $this->replace ?? [], $this->data ?? []))) { + $content = $this->buildContent($class, $this->replace ?? [], $this->data ?? []); + if (!$this->writeFile($path, $content)) { CLI::error(self::ARROW_SYMBOL . 'File Error: ' . realpath($path) . ' ❌ ', 'light_gray'); - CLI::newLine(); return; } if ($this->getOption('force') && $isFile) { - CLI::write(self::ARROW_SYMBOL . 'File Over write: ' . realpath($path) . ' 🤙', 'yellow'); - CLI::newLine(); + CLI::write(self::ARROW_SYMBOL . 'File Overwrite: ' . realpath($path) . ' 🤙', 'yellow'); return; } - CLI::write(self::ARROW_SYMBOL . 'File Create: ' . realpath($path) . ' 🤙', 'green'); + CLI::write(self::ARROW_SYMBOL . 'File Created: ' . realpath($path) . ' 🤙', 'green'); + } + + private function promptUserToContinue(string $namespace): void + { + CLI::write(self::ARROW_SYMBOL . "CLI generator using [ $namespace ] Namespace. ⚠ ", 'yellow'); + CLI::newLine(); + + if (CLI::prompt(self::ARROW_SYMBOL . 'Are you sure you want to continue? ❓ ', ['y', 'n'], 'required') === 'n') { + CLI::newLine(); + CLI::write(self::ARROW_SYMBOL . 'CLI generator cancelled', 'yellow'); + CLI::newLine(); + exit; + } + CLI::newLine(); } + private function createDirectory(string $directory): void + { + if (!is_dir($directory)) { + mkdir($directory, 0755, true); + } + } + + private function writeFile(string $path, string $content): bool + { + helpers('filesystem'); + return writeFile($path, $content); + } + /** * Prepare options and do the necessary replacements. */ @@ -190,43 +181,28 @@ protected function basename(string $filename): string */ protected function qualifyClassName(): string { - // Gets the class name from input. - $class = CLI::getSegment(2) ?? $this->className ?? null; + $className = CLI::getSegment(2) ?? $this->className; - if ($class === null && $this->hasClassName) { - $nameLang = $this->classNameLang ?: ' Class name ❓'; - $class = CLI::prompt($nameLang, null, 'required'); - CLI::newLine(); + if ($className === null && $this->hasClassName) { + $className = CLI::prompt('Class name ❓', null, 'required'); } helpers('inflector'); - $component = singular($this->component); + $classPattern = sprintf('/([a-z][a-z0-9_\/\\\\]+)(%s)/i', $component); - /** - * @see https://regex101.com/r/a5KNCR/1 - */ - $pattern = sprintf('/([a-z][a-z0-9_\/\\\\]+)(%s)/i', $component); - - if (preg_match($pattern, $class, $matches) === 1) { - $class = $matches[1] . ucfirst($matches[2]); + if (preg_match($classPattern, $className, $matches) === 1) { + $className = $matches[1] . ucfirst($matches[2]); } - if ($this->enabledSuffixing && $this->getOption('suffix') && !strripos($class, $component)) { - $class .= ucfirst($component); + if ($this->enabledSuffixing && $this->getOption('suffix') && !strripos($className, $component)) { + $className .= ucfirst($component); } - // Trims input, normalize separators, and ensure that all paths are in Pascalcase. - $class = ltrim(implode('\\', array_map('pascalize', explode('\\', str_replace('/', '\\', trim($class))))), '\\/'); - - // Gets the namespace from input. Don't forget the ending backslash! - $namespace = trim(str_replace('/', '\\', $this->getOption('namespace') ?? $this->namespace ?? APP_NAMESPACE), '\\') . '\\'; + $className = ltrim(implode('\\', array_map('pascalize', explode('\\', str_replace(['/', '\\'], '\\', trim($className))))), '\\'); + $namespace = trim(str_replace(['/', '\\'], '\\', $this->getOption('namespace') ?? $this->namespace ?? APP_NAMESPACE), '\\') . '\\'; - if (strncmp($class, $namespace, strlen($namespace)) === 0) { - return $class; - } - - return $namespace . $this->directory . '\\' . str_replace('/', '\\', $class); + return $namespace . $this->directory . '\\' . $className; } /** @@ -245,11 +221,6 @@ protected function renderTemplate(array $data = []): string /** * Perform replacements in a template using a single associative array of search and replace values. - * - * @param string $class The fully qualified class name. - * @param array $replacements An associative array where the keys are the search patterns and the values are the replacement strings. - * @param array $data Additional data for template rendering. - * @return string The modified template. */ protected function parseTemplate(string $class, array $replacements = [], array $data = []): string { @@ -270,11 +241,8 @@ protected function parseTemplate(string $class, array $replacements = [], array /** * Get the full namespace for a given class, without the class name. - * - * @param string $name - * @return string */ - protected function getNamespace($name) + protected function getNamespace(string $name): string { return trim(implode('\\', array_slice(explode('\\', $name), 0, -1)), '\\'); } @@ -324,7 +292,6 @@ protected function buildPath(string $class): string /** * Allows child generators to modify the internal `$hasClassName` flag. - * @return $this */ protected function setHasClassName(bool $hasClassName) { @@ -334,7 +301,6 @@ protected function setHasClassName(bool $hasClassName) /** * Allows child generators to modify the internal `$sortImports` flag. - * @return $this */ protected function setSortImports(bool $sortImports) { @@ -344,9 +310,8 @@ protected function setSortImports(bool $sortImports) /** * Allows child generators to modify the internal `$enabledSuffixing` flag. - * @return $this */ - protected function setEnabledSuffixing(bool $enabledSuffixing) + protected function setEnabledSuffixing(bool $enabledSuffixing): self { $this->enabledSuffixing = $enabledSuffixing; return $this; @@ -355,8 +320,6 @@ protected function setEnabledSuffixing(bool $enabledSuffixing) /** * Gets a single command-line option. Returns TRUE if the option exists, * but doesn't have a value, and is simply acting as a flag. - * - * @return mixed */ protected function getOption(string $name) { @@ -374,10 +337,8 @@ protected function getOption(string $name) * - Removes any characters that are not letters, numbers, or underscores. * - Ensures the first character is a letter or underscore. * - Converts the name to CamelCase format. - * @param string $className The name of the class to be formatted. - * @return string The formatted and valid PHP class name. */ - function formatClassName($className) + function formatClassName(?string $className): string { // Remove characters that are not letters, numbers, or underscores $filteredName = preg_replace('/[^\p{L}\p{N}_]/u', '', $className); diff --git a/src/libraries/Console/HelpConsole.php b/src/libraries/Console/HelpConsole.php index df449f5..5a17c41 100644 --- a/src/libraries/Console/HelpConsole.php +++ b/src/libraries/Console/HelpConsole.php @@ -7,7 +7,7 @@ * * CI Help command for the axm script. * - * Lists the basic usage information for the axm script, + * Lists the basic usage information for The axm script, * and provides a way to list help for other commands. * * @author Juan Cristobal @@ -18,52 +18,40 @@ class Help extends BaseCommand { /** - * The group the command is lumped under + * The group The command is lumped under * when listing commands. - * - * @var string */ - protected $group = 'Axm'; + protected string $group = 'Axm'; /** * The Command's name - * - * @var string */ - protected $name = 'help'; + protected string $name = 'help'; /** - * the Command's short description - * - * @var string + * The Command's short description */ - protected $description = 'Displays basic usage information.'; + protected string $description = 'Displays basic usage information.'; /** - * the Command's usage - * - * @var string + * The Command's usage */ - protected $usage = 'help command_name'; + protected string $usage = 'help command_name'; /** - * the Command's Arguments - * - * @var array + * The Command's Arguments */ - protected $arguments = [ + protected array $arguments = [ 'command_name' => 'The command name [default: "help"]', ]; /** - * the Command's Options - * - * @var array + * The Command's Options */ - protected $options = []; + protected array $options = []; /** - * Displays the help for axm commands. + * Displays The help for axm commands. */ public function run(array $params) { diff --git a/src/libraries/Encryption/Encrypter.php b/src/libraries/Encryption/Encrypter.php index 330b00c..7bad056 100644 --- a/src/libraries/Encryption/Encrypter.php +++ b/src/libraries/Encryption/Encrypter.php @@ -40,9 +40,6 @@ public function newKey(int $keyLength = 32) /** * Encrypt data. - * - * @param string $data - * @return string */ public function encrypt(string $data): string { @@ -76,9 +73,6 @@ public function encrypt(string $data): string /** * Decrypt data. - * - * @param string $encrypted_payload - * @return mixed */ public function decrypt(string $encrypted_payload) { @@ -106,9 +100,6 @@ public function decrypt(string $encrypted_payload) /** * Generate a hash based on the IV and encryption key. - * - * @param string $iv - * @return string */ protected function generateHash(string $iv): string { @@ -117,9 +108,6 @@ protected function generateHash(string $iv): string /** * Generate a random encryption key. - * - * @param int $length - * @return string */ public function generateKeyRandom(int $length): string { diff --git a/src/libraries/Http/CacheTrait.php b/src/libraries/Http/CacheTrait.php index 066d75c..147d430 100644 --- a/src/libraries/Http/CacheTrait.php +++ b/src/libraries/Http/CacheTrait.php @@ -7,11 +7,6 @@ trait CacheTrait /** * Enables response caching and sets cache options. - * - * @param bool $enableCache Whether to enable response caching. - * @param int $cacheTime The time in seconds to consider the response cache as valid. - * @param string $etag The ETag value for cache validation. - * @param int $expires The expiration time in seconds for the cached response. * @return $this */ public function enableResponseCache(bool $enableCache = true, int $cacheTime = 60, string $etag = null, int $expires = null) @@ -37,8 +32,6 @@ public function enableResponseCache(bool $enableCache = true, int $cacheTime = 6 /** * Disables response caching. - * - * @return $this */ public function disableResponseCache() { diff --git a/src/libraries/Http/Curl.php b/src/libraries/Http/Curl.php index 53300f8..9803eca 100644 --- a/src/libraries/Http/Curl.php +++ b/src/libraries/Http/Curl.php @@ -48,11 +48,6 @@ public function __construct() /** * Sends a GET request. - * - * @param string $url The URL to send the GET request to. - * @param array $headers Optional headers to include in the request. - * @return array The response and cURL info. - * @throws \Exception If there is an error in the cURL request. */ public function get(string $url, array $headers = []): array { @@ -61,9 +56,6 @@ public function get(string $url, array $headers = []): array /** * Sends a POST request. - * - * @return array The response and cURL info. - * @throws \Exception If there is an error in the cURL request. */ public function post(string $url, array $data = [], array $headers = []): array { @@ -72,9 +64,6 @@ public function post(string $url, array $data = [], array $headers = []): array /** * Sends a PUT request. - * - * @return array The response and cURL info. - * @throws \Exception If there is an error in the cURL request. */ public function put(string $url, array $data = [], array $headers = []): array { @@ -83,9 +72,6 @@ public function put(string $url, array $data = [], array $headers = []): array /** * Sends a DELETE request. - * - * @return array The response and cURL info. - * @throws \Exception If there is an error in the cURL request. */ public function delete(string $url, array $data = [], array $headers = []): array { @@ -94,9 +80,6 @@ public function delete(string $url, array $data = [], array $headers = []): arra /** * Sends a HEAD request. - * - * @return array The response and cURL info. - * @throws \Exception If there is an error in the cURL request. */ public function head(string $url, array $headers = []): array { @@ -105,9 +88,6 @@ public function head(string $url, array $headers = []): array /** * Performs the cURL request. - * - * @return array The response and cURL info. - * @throws \Exception If there is an error in the cURL request. */ private function request(string $method, string $url, array $data = [], array $headers = []) { @@ -137,7 +117,6 @@ private function request(string $method, string $url, array $data = [], array $h /** * Builds the response array. - * @return array The response and cURL info. */ private function buildResponse(string $response, array $info): array { @@ -161,7 +140,6 @@ private function setCommonOptions(string $url, string $method): bool /** * Sets a cURL option. - * @param mixed $value The value to set for the option. */ public function setCurlOption(int $option, $value) { @@ -181,9 +159,8 @@ private function setRequestBody(array $data, string $contentType = 'array') /** * Prepares POST data for the request. - * @return mixed The prepared data. */ - private function preparePostData(array $data, string $contentType = 'json') + private function preparePostData(array $data, string $contentType = 'json'): mixed { return match ($contentType) { 'json' => json_encode($data), @@ -300,7 +277,6 @@ public function multiExec(array $handles) /** * Sets the number of retry attempts in case of failures. - * @param int $attempts The number of retry attempts. */ public function setRetryAttempts(int $attempts) { @@ -310,7 +286,6 @@ public function setRetryAttempts(int $attempts) /** * Sets the HTTP status codes considered as transient errors for retry attempts. - * @param array $codes The array of HTTP status codes. */ public function setTransientErrorCodes(array $codes) { diff --git a/src/libraries/Http/OAuthTrait.php b/src/libraries/Http/OAuthTrait.php index eb7a90a..25a7f32 100644 --- a/src/libraries/Http/OAuthTrait.php +++ b/src/libraries/Http/OAuthTrait.php @@ -7,9 +7,6 @@ trait OAuthTrait { /** * Sets the OAuth token for authentication. - * - * @param string $token The OAuth token. - * @return $this */ public function setOAuthToken(string $token) { @@ -19,9 +16,6 @@ public function setOAuthToken(string $token) /** * Sets the OAuth token secret for authentication. - * - * @param string $tokenSecret The OAuth token secret. - * @return $this */ public function setOAuthTokenSecret(string $tokenSecret) { diff --git a/src/libraries/Http/Promise.php b/src/libraries/Http/Promise.php index 7429c20..9b8d2c8 100644 --- a/src/libraries/Http/Promise.php +++ b/src/libraries/Http/Promise.php @@ -36,10 +36,6 @@ public function __construct() /** * Attaches a callback to be executed when the promise is fulfilled or rejected. - * - * @param callable $onFulfilled Callback to execute when the promise is fulfilled. - * @param callable|null $onRejected Callback to execute when the promise is rejected. - * @return PromiseInterface */ public function then(callable $onFulfilled, callable $onRejected = null): PromiseInterface { @@ -66,7 +62,6 @@ public function then(callable $onFulfilled, callable $onRejected = null): Promis /** * Handles the result of a callback. - * @param mixed $result Result of the callback. */ private function handleCallbackResult($result) { @@ -86,11 +81,8 @@ function ($reason) { /** * Resolves the promise with a value. - * - * @param mixed $result Value to resolve the promise with. - * @return PromiseInterface */ - public function resolve($result): PromiseInterface + public function resolve(mixed $result): PromiseInterface { $this->validateResolveOrRejectArgument($result); @@ -112,11 +104,8 @@ public function resolve($result): PromiseInterface /** * Rejects the promise with a reason. - * - * @param mixed $reason Reason to reject the promise with. - * @return PromiseInterface */ - public function reject($reason): PromiseInterface + public function reject(mixed $reason): PromiseInterface { $this->validateResolveOrRejectArgument($reason); @@ -138,9 +127,6 @@ public function reject($reason): PromiseInterface /** * Creates a promise that is resolved with the result of a callback. - * - * @param callable $callback Callback to execute. - * @return PromiseInterface */ public static function async(callable $callback): PromiseInterface { @@ -161,9 +147,6 @@ public static function async(callable $callback): PromiseInterface /** * Waits for multiple promises to settle and returns an array of their results. - * - * @param array $promises Promises to wait for. - * @return PromiseInterface */ public static function all(array $promises): PromiseInterface { @@ -195,9 +178,6 @@ function ($reason) use (&$count) { /** * Attaches a callback to be executed when the promise settles, regardless of whether it is fulfilled or rejected. - * - * @param callable $onFinally Callback to execute when the promise settles. - * @return PromiseInterface */ public function finally(callable $onFinally): PromiseInterface { @@ -207,7 +187,7 @@ public function finally(callable $onFinally): PromiseInterface function ($result) use ($onFinally) { try { $onFinally(); - } catch (\Throwable $th) { + } catch (Throwable $th) { throw $th; } return $result; @@ -221,9 +201,6 @@ function ($reason) use ($onFinally) { /** * Validates the arguments passed to the `then` method. - * - * @param callable $onFulfilled Callback to execute when the promise is fulfilled. - * @param callable|null $onRejected Callback to execute when the promise is rejected. */ private function validateThenArguments(callable $onFulfilled, callable $onRejected = null): void { @@ -238,9 +215,8 @@ private function validateThenArguments(callable $onFulfilled, callable $onReject /** * Validates the argument passed to the `resolve` and `reject` methods. - * @param mixed $argument Argument to validate. */ - private function validateResolveOrRejectArgument($argument): void + private function validateResolveOrRejectArgument(mixed $argument): void { if ($argument === null || is_scalar($argument)) { return; @@ -253,7 +229,6 @@ private function validateResolveOrRejectArgument($argument): void /** * Validates the callback passed to the `async` method. - * @param callable $callback Callback to validate. */ private static function validateAsyncCallback(callable $callback): void { @@ -264,7 +239,6 @@ private static function validateAsyncCallback(callable $callback): void /** * Validates the array of promises passed to the `all` method. - * @param array $promises Array of promises to validate. */ private static function validatePromisesArray(array $promises): void { @@ -277,7 +251,6 @@ private static function validatePromisesArray(array $promises): void /** * Validates the callback passed to the `finally` method. - * @param callable $callback Callback to validate. */ private function validateFinallyCallback(callable $callback): void { diff --git a/src/libraries/Http/ProxyTrait.php b/src/libraries/Http/ProxyTrait.php index b52ffb0..2fbd510 100644 --- a/src/libraries/Http/ProxyTrait.php +++ b/src/libraries/Http/ProxyTrait.php @@ -7,11 +7,6 @@ trait ProxyTrait /** * Sets the proxy for the cURL request. - * - * @param string $proxy The proxy URL. - * @param string|null $username Optional username for proxy authentication. - * @param string|null $password Optional password for proxy authentication. - * @return $this */ public function setProxy(string $proxy, ?string $username = null, ?string $password = null) { @@ -26,9 +21,6 @@ public function setProxy(string $proxy, ?string $username = null, ?string $passw /** * Sets the cURL option to tunnel through a proxy. - * - * @param int $tunnel The tunnel option (1 to enable, 0 to disable). - * @return $this */ public function tunnelThroughProxy(int $tunnel = 1) { diff --git a/src/libraries/Http/Request.php b/src/libraries/Http/Request.php index 00ba312..d489cdf 100644 --- a/src/libraries/Http/Request.php +++ b/src/libraries/Http/Request.php @@ -40,6 +40,7 @@ class Request extends URI 'application/json' => 'parseJSON', 'application/xml' => 'parseXML', 'application/x-www-form-urlencoded' => 'parseForm', + 'multipart/form-data' => 'parseMultipartForm' ]; /** @@ -58,6 +59,16 @@ public function __construct() $this->init(); } + /** + * Parse multipart/form-data request + */ + public function parseMultipartForm(): array + { + $formData = compact($this->post(), $this->files()) ?? []; + + return $formData; + } + /** * Create a URL by combining a base URL and a relative URI. */ @@ -79,7 +90,9 @@ public function getMethod(): ?string */ public function files(string $name = null): ?array { - return $name !== null ? $_FILES[$name] ?? null : $_FILES; + $files = isset($_FILES) ? $this->getFilteredValue($name, $_FILES) : null; + + return $name !== null ? $files[$name] ?? null : $files; } /** @@ -525,6 +538,14 @@ public function get(string $key = '') return isset($_GET) ? $this->getFilteredValue($key, $_GET) : null; } + /** + * Gets a value from the $_POST array, applies the default FILTER_SANITIZE_STRING filter + */ + public function post(string $key = '') + { + return isset($_POST) ? $this->getFilteredValue($key, $_POST) : null; + } + /** * Gets a value $value from the array $_REQUEST(Contains $_GET,$_POST,$_COOKIE) */ diff --git a/src/libraries/Http/URI.php b/src/libraries/Http/URI.php index 3f35593..c84f4ce 100644 --- a/src/libraries/Http/URI.php +++ b/src/libraries/Http/URI.php @@ -425,44 +425,4 @@ private function generateSignature(string $url): string $signature = hash_hmac(self::HASH_ALGORITHM, $dataToSign, $this->key); return $signature; } - - /** - * Removes a specified number of path fragments from a given path. - * - * This function divides the input path into fragments using the directory separator (e.g., '/') as a separator. - * It then calculates the total number of fragments in the path and removes fragments either from the left (positive count) - * or the right (negative count) side of the path. If the count is 0, no fragments are removed. - * @example - * $originalPath = "C:/xampp/htdocs/appApp/vendor/axm/raxm/src"; - * $modifiedPath = removePathFragments($originalPath, -3); - * return "C:/xampp/htdocs/appApp" - */ - public function removePathFragments(string $path, int $count): string - { - // Split the path into fragments using the directory separator. - $fragments = explode(DIRECTORY_SEPARATOR, $path); - - // Calculate the total number of fragments in the path. - $totalFragments = count($fragments); - - // Determine whether to remove fragments from the left or right. - if ($count > 0) { - // Remove fragments from the left. - $resultFragments = array_slice($fragments, $count); - } elseif ($count < 0) { - // Calculate the number of fragments to remove from the right. - $removeCount = abs($count); - - // Remove fragments from the right. - $resultFragments = array_slice($fragments, 0, $totalFragments - $removeCount); - } else { - // If $count is 0, no fragments are removed. - $resultFragments = $fragments; - } - - // Reconstruct the path from the remaining fragments. - $resultPath = implode(DIRECTORY_SEPARATOR, $resultFragments); - - return $resultPath; - } -} +} \ No newline at end of file diff --git a/src/libraries/Lang/Lang.php b/src/libraries/Lang/Lang.php index 4881979..7982045 100644 --- a/src/libraries/Lang/Lang.php +++ b/src/libraries/Lang/Lang.php @@ -18,17 +18,11 @@ interface LangInterface { /** * Get the current locale. - * - * @return string The current locale. */ public function getLocale(): string; /** * Translate a key with optional parameters. - * - * @param string $key The translation key. - * @param array $params Optional parameters for string interpolation. - * @return string The translated message. */ public function trans(string $key, array $params = []): string; } @@ -77,8 +71,6 @@ public function setLocale(): void /** * Get the current locale. - * - * @return string The current locale. */ public function getLocale(): string { @@ -87,10 +79,6 @@ public function getLocale(): string /** * Translate a key with optional parameters. - * - * @param string $key The translation key. - * @param array $params Optional parameters for string interpolation. - * @return string The translated message. */ public function trans(string $key, array $params = []): string { @@ -109,8 +97,6 @@ public function trans(string $key, array $params = []): string /** * Load translations from language files. - * - * @throws RuntimeException If an error occurs while loading language files. */ public function loadTranslationsFromFile(): void { diff --git a/src/libraries/Middlewares/AuthMiddleware.php b/src/libraries/Middlewares/AuthMiddleware.php index ced92cf..c4fb55e 100644 --- a/src/libraries/Middlewares/AuthMiddleware.php +++ b/src/libraries/Middlewares/AuthMiddleware.php @@ -22,9 +22,6 @@ class AuthMiddleware extends BaseMiddleware /** * __construct * - * @param mixed $actions - * @param mixed $allowedAction - * @return void */ public function __construct(array $actions = [], bool $allowedAction = self::NOT_ALLOWED_ACTION) { @@ -34,7 +31,6 @@ public function __construct(array $actions = [], bool $allowedAction = self::NOT /** * Execute the action, checking authentication and permissions. - * @throws RuntimeException If the user does not have sufficient permissions. */ public function execute() { @@ -45,9 +41,6 @@ public function execute() /** * Validates if the user has permissions to access the current action. - * - * @throws RuntimeException If the user doesn't have permissions - * to access the current action. */ private function validatePermission() { @@ -65,7 +58,6 @@ private function validatePermission() /** * Throws a RuntimeException indicating insufficient permissions. - * @throws RuntimeException If the user does not have sufficient permissions. */ private function throwPermissionException() { diff --git a/src/libraries/Middlewares/MaintenanceMiddleware.php b/src/libraries/Middlewares/MaintenanceMiddleware.php index 77d0575..89bb441 100644 --- a/src/libraries/Middlewares/MaintenanceMiddleware.php +++ b/src/libraries/Middlewares/MaintenanceMiddleware.php @@ -14,25 +14,24 @@ class MaintenanceMiddleware extends BaseMiddleware /** * Checks if the user is authenticated and has * permissions to access the current action. - * - * @return void */ public function execute() { $maintenance = env('APP_DOWN', false); if ($maintenance === true) - return $this->showViewMaintenance(); + return $this->showMaintenanceView(); } /** * Displays the maintenance view. - * @return void */ - private function showViewMaintenance() + private function showMaintenanceView() { - $viewFile = config('paths.viewsErrorsPath') . - DIRECTORY_SEPARATOR . config('view.errorPages.503'); + $errorViewPath = config('paths.viewsErrorsPath'); + $maintenanceView = config('view.errorPages.503'); + + $viewFile = $errorViewPath . DIRECTORY_SEPARATOR . $maintenanceView; $output = app()->controller->renderView($viewFile); - die($output); + exit($output); } } diff --git a/src/libraries/Session/Session.php b/src/libraries/Session/Session.php index f4430a4..6531b9d 100644 --- a/src/libraries/Session/Session.php +++ b/src/libraries/Session/Session.php @@ -21,7 +21,6 @@ class Session implements SessionHandlerInterface /** * Constructor. - * @param mixed $key The session key. */ public function __construct($key = null) { @@ -31,7 +30,6 @@ public function __construct($key = null) /** * Initializes the session. - * @return void */ public function init(): void { @@ -40,10 +38,6 @@ public function init(): void /** * Opens the session. - * - * @param string|null $savePath The path where session data is stored. If null, the default storage path is used. - * @param string $sessionName The name of the session (default: 'axmSesionApp'). - * @return bool True if the session is successfully opened, false otherwise. */ public function open(string $savePath = null, string $sessionName = 'axmSesionApp'): bool { @@ -60,9 +54,6 @@ public function open(string $savePath = null, string $sessionName = 'axmSesionAp /** * Reads the session data. - * - * @param string $sessionId The session ID. - * @return string The session data. */ public function read(string $sessionId): string { @@ -71,21 +62,14 @@ public function read(string $sessionId): string /** * Deletes the session data. - * - * @param string $sessionId The session ID. - * @return bool True if the session data is successfully deleted, false otherwise. */ - public function delete(string $sessionId) + public function delete(string $sessionId): bool { return $this->remove($sessionId); } /** * Writes session data. - * - * @param string $sessionId The session ID. - * @param string $data The session data. - * @return bool True if the session data is successfully written, false otherwise. */ public function write(string $sessionId, string $data): bool { @@ -94,7 +78,6 @@ public function write(string $sessionId, string $data): bool /** * Closes the session. - * @return bool True if the session is successfully closed, false otherwise. */ public function close(): bool { @@ -103,9 +86,6 @@ public function close(): bool /** * Destroys a session. - * - * @param string $sessionId The session ID. - * @return bool True if the session is successfully destroyed, false otherwise. */ public function destroy(string $sessionId): bool { @@ -115,9 +95,6 @@ public function destroy(string $sessionId): bool /** * Performs garbage collection on the session. - * - * @param int $maxLifeTime The maximum lifetime of a session. - * @return int The session expiration configuration. */ public function gc(int $maxLifeTime): int { @@ -127,7 +104,6 @@ public function gc(int $maxLifeTime): int /** * Creates the $_SESSION flash messages. - * @return void */ public function sessionFlashMessage() { @@ -136,7 +112,6 @@ public function sessionFlashMessage() /** * Destroys the current session. - * @return void */ public function clear() { @@ -145,7 +120,6 @@ public function clear() /** * Returns the session ID. - * @return string */ public function sessionId() { @@ -154,9 +128,6 @@ public function sessionId() /** * Regenerates the session ID. - * - * @param bool $destroy Should old session data be destroyed? - * @return void */ public function regenerate(bool $destroy = false) { @@ -166,12 +137,8 @@ public function regenerate(bool $destroy = false) /** * Modifies a message in the $_SESSION flash_messages. - * - * @param string $key - * @param mixed $message - * @return void */ - public function setFlash($key, $message) + public function setFlash(string $key, $message) { $_SESSION[self::FLASH_KEY][$key] = [ 'remove' => false, @@ -181,33 +148,22 @@ public function setFlash($key, $message) /** * Gets the value of a flash message. - * - * @param string $key - * @return mixed|false The value of the flash message, or false if not set. */ - public function getFlashValue($key) + public function getFlashValue(string $key): ?bool { return $_SESSION[self::FLASH_KEY][$key]['value'] ?? false; } /** * Gets a flash message. - * - * @param string $key - * @return mixed|false The flash message, or false if not set. */ - public function getFlash($key) + public function getFlash($key): ?bool { return $_SESSION[self::FLASH_KEY][$key] ?? false; } /** * Modifies a session variable. - * - * @param string $key - * @param mixed $value - * @param bool $encrypt Whether to encrypt the value. - * @return bool True if the session variable is successfully set, false otherwise. */ public function set(string $key, $value, bool $encrypt = false): bool { @@ -221,10 +177,6 @@ public function set(string $key, $value, bool $encrypt = false): bool /** * Gets the value of a session variable. - * - * @param string $key - * @param bool $decrypt Whether to decrypt the value. - * @return mixed|null The value of the session variable, or null if not set. */ public function get(string $key, bool $decrypt = false) { @@ -238,23 +190,16 @@ public function get(string $key, bool $decrypt = false) /** * Checks if a session variable is set. - * - * @param string $key - * @return bool True if the session variable is set, false otherwise. */ - public function has($key): bool + public function has(string $key): bool { return isset($_SESSION[$key]); } /** * Gets the value of a session variable and removes it from the session. - * - * @param string $key - * @param mixed $default The default value if the key is not set. - * @return mixed The value of the session variable. */ - public function pull($key, $default = null) + public function pull(string $key, $default = null) { $value = $this->get($key, $default); $this->remove($key); @@ -264,18 +209,14 @@ public function pull($key, $default = null) /** * Gets all session variables. - * @return array All session variables. */ - public function all() + public function all(): array { return $_SESSION; } /** * Removes the specified session or all sessions if $key is empty. - * - * @param string $key - * @return bool */ public function remove(string $key = ''): bool { @@ -292,8 +233,6 @@ public function remove(string $key = ''): bool /** * Destructor method called when the object is no longer referenced. * Removes expired flash messages after displaying them. - * - * @return void */ public function __destruct() { @@ -302,7 +241,6 @@ public function __destruct() /** * Gets the current time as a Unix timestamp. - * @return int The current time as a Unix timestamp. */ private function getCurrentTime(): int { @@ -311,7 +249,6 @@ private function getCurrentTime(): int /** * Removes expired flash messages after displaying them. - * @return void */ private function removeExpiredFlashMessages() { @@ -322,7 +259,6 @@ private function removeExpiredFlashMessages() /** * Frees all session variables. - * @return void */ public function flush() { @@ -332,13 +268,8 @@ public function flush() /** * Monitors session inactivity time and redirects to the specified URL * if it exceeds the given session expiration time. - * - * @param string $key - * @param string $url - * @param int $sessionExpiration - * @return bool True if the session expired, false otherwise. */ - public function police(string $key, string $url = '', int $sessionExpiration = 300) + public function police(string $key, string $url = '', int $sessionExpiration = 300): bool { $currentTime = $this->getCurrentTime(); @@ -361,8 +292,6 @@ public function police(string $key, string $url = '', int $sessionExpiration = 3 /** * Handles the expiration by logging out if the URL is empty * or redirecting to the specified URL. - * - * @param string|null $url The URL to redirect to in case it is not empty. */ private function handleExpiration(?string $url = null): void { @@ -371,10 +300,6 @@ private function handleExpiration(?string $url = null): void /** * Checks if the countdown session time has reached the specified limit. - * - * @param string $key - * @param int $time - * @return bool True if the countdown session time has reached the limit, false otherwise. */ public function countDownSession(string $key, int $time): bool {