<?php
/**
* The Handler class is responsible for managing custom error handling within the system.
* It provides methods to throw specific errors, handle exceptions, and manage PDOExceptions.
*/
namespace Mavera;
use /**
* CustomException is a base exception class for handling application-specific exceptions.
*
* This class extends the base PHP Exception class and can be used to define
* custom error codes, messages, and behaviors for exceptions specific to the application logic.
*/
Exception;
use /**
* Represents an exception thrown by the PDO extension.
*
* The PDOException class provides information about errors that occur
* during the operation of PDO methods, such as database connection failures
* or query errors. Typically, it contains the error message and the error code,
* which can be used to debug issues related to database interactions.
*
* The exception can also include a `previous` exception if chaining is used,
* providing a stack trace of the root cause of the error.
*
* It extends the `Exception` class, meaning it inherits standard exception
* functionality and can be caught and handled like other exceptions in PHP.
*/
PDOException;
use /**
* Interface Throwable
*
* Represents errors and exceptions in PHP. Every exception or error implements this interface,
* which allows them to be treated in a consistent manner. Throwable encompasses both
* Error and Exception, providing shared methods for dealing with these runtime conditions.
*
* Methods within this interface provide information about the error or exception,
* including messages, codes, and stack traces.
*
* Implementations:
* - Exception
* - Error
*
* Key Characteristics:
* - Throwable objects are caught using try...catch blocks.
* - It facilitates debugging and logging by providing detailed context for the error or
* exception state.
*/
Throwable;
/**
* Class Handler
*
* Provides methods to handle and throw exceptions based on predefined error codes or custom exceptions.
*/
class Handler
{
private static array $errors = [
3000 => "The controller file does not exist in the system.",
3001 => "The controller class is not defined.",
3002 => "Method does not exist.",
3003 => "The parameters sent do not comply with this method.",
3004 => "The gateway controller did not allow access.",
3005 => "View render file not found.",
3006 => "There is no middleware file.",
3007 => "Middleware class is faulty.",
3008 => "Middleware handle function does not exist.",
3009 => "Request method is not appropriate.",
6001 => "Critical Log file cannot be created. Contact the system administrator!",
6002 => "Critical Log file cannot be opened. Contact the system administrator!",
7001 => "Invalid definition in route setting.",
];
static function e(int $code, string $extra = null)
{
throw new Exception(trim((self::$errors[$code] ?? ($extra === null ? "An Unexpected Error" : '')) . " " . $extra), $code);
}
static function catch(Throwable $th)
{
throw new Exception($th->getMessage(), $th->getCode(), $th);
}
static function catch_pdo_exception(PDOException $e)
{
throw $e;
}
}
<?php
/**
* The App class is responsible for handling and managing the application's routing,
* initialization, and view engine configuration. It serves as the main entry point
* for the application, ensuring that incoming requests are appropriately routed
* and processed.
*/
namespace TULGAR\Base\Framework;
use Exception;
use Mavera\{/**
* The Handler class serves as the base class for implementing
* a chain-of-responsibility pattern. It provides functionality
* to process requests and optionally delegate them to the next
* handler in the chain.
*/
Handler,
/**
* Interface Middleware
*
* Represents a middleware in a middleware pipeline.
* Middleware is responsible for handling incoming requests,
* processing them, and producing appropriate responses.
*
* Middleware may perform tasks such as authentication,
* logging, request transformation, or delegation to the next
* middleware in the pipeline.
*
* To be implemented by classes intending to define custom
* middleware behavior.
*/
Middleware,
/**
* Router class
*
* The Router class is responsible for handling and managing application routes.
* It matches incoming requests to the appropriate callback functions or controllers,
* enabling the application to handle different URLs gracefully.
*/
Router,
/**
* Class URL
*
* Represents a URL and provides methods to parse, manipulate, and retrieve components of the URL.
*
* Methods typically include functionality to construct a URL from different parts,
* parse an existing URL string, retrieve individual components such as the protocol,
* host, path, query parameters, and to modify or manipulate the URL as needed.
*/
URL
};
use /**
* Specifies that this function or method does not return to the caller.
* Instead, the function halts execution, either by throwing an exception or terminating the script.
* Useful for indicating that a method is expected to stop program flow.
*
* This annotation is provided by JetBrains PhpStorm and improves static code analysis.
* It is non-functional, meaning it does not affect runtime behavior.
*/
JetBrains\PhpStorm\NoReturn;
use ReflectionMethod;
use /**
* The Framework class provides foundational functionality for the TULGAR Addons system.
*
* This class includes methods and properties that are common to all addon
* implementations within the TULGAR ecosystem. It is intended to be extended
* by other classes that build upon its structure and functionality.
*
* Responsibilities of this class include managing shared resources, providing
* utility methods, and serving as a base class for addon-specific logic.
*/
TULGAR\Addons\Framework;
use /**
* The View class serves as the core component responsible for rendering and managing views in the TULGAR application framework.
* This class handles loading template files, populating data into views, and managing the relationship between controllers and their corresponding views.
*
* Responsibilities:
* - Handles view file rendering
* - Passes data from controllers to the view
* - Serves as an interface between the presentation layer and the application's logic
*
* Typical usage involves linking a view to a controller, rendering templates, and displaying dynamic data in the UI.
*
* Note:
* Ensure that the view files are correctly located and accessible by the file system to prevent failures in rendering.
*/
TULGAR\Core\View;
use Twig\Loader\FilesystemLoader;
use const Mavera\Config\Application\MAIN_NAMESPACE;
use const /**
* Constant VIEW_BASE
*
* Defines the base directory path for the application's views.
* This constant is used as a reference for locating view files
* throughout the application.
*
* @const string
*/
Mavera\Config\Application\VIEW_BASE;
/**
* The App class represents the primary controller handling the execution
* of application routes and operations such as initializing and finalizing
* main application workflows. This class processes incoming requests,
* resolves routes, invokes appropriate controllers/actions, and manages view rendering.
*/
class App
{
/**
* Handles the application's initial routing and controller/action initialization.
* This method processes the incoming request, resolves the appropriate route, and
* executes the corresponding controller action. It also handles static and dynamic
* routing logic, middleware execution, and prepares the environment for the
* application's operation.
*
* @return null
* @throws Exception
*/
function Start(): null
{
$folder = BASE . "App/";
$controller_name = "Home";
$action = "Index";
$q = isset($_GET["q"]) ? trim(ltrim(rtrim($_GET["q"], '/'), '/')) : "";
$q = strlen($q) > 0 ? explode("/", $q) : [];
if (count($q) == 0) {
$q = [$controller_name, $action];
}
Router::$route = $q;
unset($q);
/* Static Route Operations -- */
foreach (Router::$routes as $method => $routes) {
foreach ($routes as $route => $callback) {
if ($_SERVER['REQUEST_METHOD'] == $method) {
/* There is no callable callback this route. */
if (!is_callable($callback)) return Handler::e(7001);
$route_parts = explode('/', rtrim(ltrim($route, '/'), '/'));
if ($route_parts[0] == '' && count(Router::$route) == 0) {
Router::$raw_route = $route;
$this->Init();
call_user_func_array($callback, []);
$this->End();
}
if (count($route_parts) != count(Router::$route)) {
continue;
}
$params = [];
$rok = true;
for ($i = 0; $i < count($route_parts); $i++) {
$part = $route_parts[$i];
if (preg_match("/^[$]/", $part)) {
$part = ltrim($part, '$');
$params[] = Router::$route[$i];
$$part = Router::$route[$i];
} else if ($route_parts[$i] != Router::$route[$i]) {
$rok = false;
}
}
if ($rok) {
Router::$raw_route = $route;
Router::$params = $params;
$this->Init();
call_user_func_array($callback, $params);
$this->End();
}
}
}
}
/* Static Route Operations -- */
$prefixes = (object)[
"function" => "",
"folder" => MAIN_NAMESPACE . "/"
];
$_route = [];
if (count(Router::$route) > 0) if (isset(URL::get()[strtolower(Router::$route[0])])) {
Router::$URL = strtolower(Router::$route[0]);
$_tmp = URL::get()[strtolower(Router::$route[0])];
$prefixes->function = $_tmp["Prefix"];
$prefixes->folder = $_tmp["Folder"];
unset($_tmp);
$_route[] = Router::$route[0];
array_shift(Router::$route);
}
if (count(Router::$route) > 0) {
$controller_name = Router::$route[0];
$_route[] = Router::$route[0];
array_shift(Router::$route);
if (count(Router::$route) > 0) {
$action = Router::$route[0];
$_route[] = Router::$route[0];
array_shift(Router::$route);
}
}
Router::$params = Router::$route;
Router::$route = $_route;
if (empty(Router::$URL))
Router::$URL = strtolower(MAIN_NAMESPACE);
unset($_route);
$class_name = Framework::Url2Class($controller_name);
$action = $prefixes->function . Framework::Url2Class($action);
if (isset(Router::$route_config[strtolower($class_name)][strtolower($action)])) if ($_SERVER['REQUEST_METHOD'] != Router::$route_config[strtolower($class_name)][strtolower($action)]) return Handler::e(3009, "Only " . Router::$route_config[strtolower($class_name)][strtolower($action)] . " method is accepted.");
$file = Framework::File_Control($folder . "Controllers/" . $prefixes->folder . str_replace('-', '_', $controller_name) . ".php");
if (!$file) {
return Handler::e(3000);
}
Framework::Prepare_Files(["Controller"], "System/Core");
require_once $file;
$class_tulgar = "App\\Controllers\\" . Framework::Url2Class(Router::$URL) . "\\" . $class_name;
if (!class_exists($class_tulgar)) {
return Handler::e(3001);
}
$controller = new $class_tulgar();
if (!method_exists($controller, $action)) {
return Handler::e(3002);
}
Router::$route = array_merge(Router::$route, Router::$params);
$actionParam = (new ReflectionMethod($controller, $action))->getNumberOfParameters();
$actionRequiredParam = (new ReflectionMethod($controller, $action))->getNumberOfRequiredParameters();
$param = count(Router::$params);
if (($param == 0 && $actionRequiredParam == 0) || ($param >= $actionRequiredParam && $param <= $actionParam)) {
Framework::Prepare_Folder("App/Helpers");
Framework::Prepare_Files(["Model"], "System/Core");
Framework::Prepare_Folder("App/Models");
Router::$raw_class = $class_name;
Router::$raw_action = $action;
Middleware::handle('route');
Framework::Prepare_Files(["View"], "System/Core");
$this->ConfigViewEngine();
Framework::Prepare_Folder("App/Includes/General", null, true);
if (Router::$URL !== null) {
if (file_exists(BASE . "App/Includes/URL/" . Router::$URL)) {
Framework::Prepare_Folder("App/Includes/URL/" . Router::$URL);
}
}
call_user_func_array([$controller, $action], Router::$params);
$this->End();
} else {
return Handler::e(3003);
}
}
/**
* Configures the view engine by setting up the Twig loader with the defined view base path.
*
* @return void
* @throws Exception
*/
function ConfigViewEngine(): void
{
View::SetEngine(new FilesystemLoader(VIEW_BASE));
}
/**
* Initializes the framework by preparing necessary folders, configuring the view engine,
* and handling middleware for static requests. Additionally, this method prepares
* specific folders if a URL-based include is detected.
*
* @return void
* @throws Exception
*/
function Init(): void
{
Framework::Prepare_Folder("System/Core");
$this->ConfigViewEngine();
Framework::Prepare_Folder("App/Helpers");
Framework::Prepare_Folder("App/Models");
Middleware::handle('static');
Framework::Prepare_Folder("App/Includes/General", null, true);
if (Router::$URL !== null) {
if (file_exists(BASE . "App/Includes/URL/" . Router::$URL)) {
Framework::Prepare_Folder("App/Includes/URL/" . Router::$URL);
}
}
}
/**
* Terminates the current script execution.
*
* @return void This function does not return any value as it halts execution using exit().
*/
#[NoReturn] function End(): void
{
exit();
}
}
<?php
/**
* The beginning of everything.
* This is pure magic! 😍
*
* Author: Ahmet Tulgar
* Powered by PULP!
*/
use /**
* This namespace contains the classes and interfaces that comprise the Framework part of the Addons system.
* It is designed to provide reusable components and tools to be utilized in building additional features or extensions.
*
* The TULGAR\Addons\Framework namespace may include base classes, abstract classes, services,
* and utilities that help standardize and manage addon-specific functionalities.
*/
TULGAR\Addons\Framework;
use /**
* The App class serves as the core application framework in the TULGAR\Base\Framework namespace.
* It manages the initialization and execution process of the framework, ensuring proper configuration
* and bootstrapping of components required for the application to function.
*
* Responsibilities of this class may include:
* - Managing configuration settings and environment variables.
* - Initializing services or components required for the application.
* - Handling request and response flow.
* - Acting as a central point of control for the framework operations.
*/
TULGAR\Base\Framework\App;
use /**
* Represents a custom exception class for handling PHP-specific exceptions.
*
* This class extends the base Exception class to provide specialized error
* handling for PHP-related exceptions. It facilitates creating and managing
* custom exception messages, codes, and contexts specific to PHP operations.
*
* Use this class to throw and catch PHP exceptions in place of the default
* Exception class when more granularity and specificity are needed for error
* reporting and debugging.
*
* Methods for manipulation and retrieval of exception details such as the
* message, code, file, and line are inherited from the base Exception class.
*/
TULGAR\Base\Exception\PHPException;
session_start();
setlocale(LC_TIME, "turkish.UTF-8");
setlocale(LC_MONETARY, "tr_TR");
date_default_timezone_set("Europe/Istanbul");
/**
* Constant PROTOCOL
*
* Defines the protocol to be used, which is set to 'https'.
* This constant ensures secure communication by using
* the HTTPS protocol for data transmission.
*/
const PROTOCOL = 'https';
/**
* Defines a constant named SITE.
* SITE is constructed by concatenating the protocol, server name, and a trailing slash.
*
* The constant dynamically retrieves the server's protocol using a pre-defined constant (PROTOCOL),
* and appends it with the server's host name retrieved from the `$_SERVER['SERVER_NAME']` global variable.
* Ensures the site URL structure is consistent and accessible across the application.
*/
define("SITE", PROTOCOL . '://' . $_SERVER['SERVER_NAME'] . '/');
/**
* Class responsible for managing and interacting with the framework's directory.
*
* FRAMEWORK_DIRECTORY is a constant representing the root directory of the framework.
*/
const FRAMEWORK_DIRECTORY = '';
/**
* Concatenates the SITE constant with the FRAMEWORK_DIRECTORY constant to create the SITE_URL constant.
*
* SITE_URL: Represents the full URL path that combines the base site URL (SITE) and the framework directory path (FRAMEWORK_DIRECTORY).
*/
const SITE_URL = SITE . FRAMEWORK_DIRECTORY;
/**
* Defines the constant ASSETS which represents the URL path to the assets' directory.
* The constant is created by concatenating the SITE_URL with the relative path 'assets/'.
* It is used to reference the assets folder within the application.
*/
const ASSETS = SITE_URL . 'assets/';
if (file_exists(BASE . "System/Composer/Vendor/autoload.php")) {
include BASE . "System/Composer/Vendor/autoload.php";
}
require_once BASE . "System/Base/Exception/Project/Bootstrap.php";
try {
$TULGAR_PHP_Exception = new PHPException([
"production_mode" => !DEBUG_SYSTEM
]);
} catch (Exception $e) {
exit('Exception handler failure. Please check system.');
}
$TULGAR_PHP_Exception->setUrl(SITE_URL . "System/Base/Exception/");
$TULGAR_PHP_Exception->start();
require_once BASE . 'System/Addons/Framework.php';
Framework::Prepare_Folder('System/Functions');
Framework::Prepare_Folder('System/Helpers');
Framework::Prepare_Folder('System/Base/System');
Framework::Prepare_Folder('System/Config', withSubFolders: true);
require_once "App.php";
{
/**
* The $app variable represents the main application instance.
* It serves as the central point of the application and is typically
* responsible for managing overall application flow, services,
* dependencies, configurations, and request handling.
*
* This variable is often used to access core functionality or services
* that have been registered within the application container.
*/
$app = new App();
/*
* abracadabra! ⚡️
*/
$app->Start();
}
<?php
/**
* Defines a constant `START_TIME` that records the current timestamp in microseconds as a float.
* This can be used for measuring execution time or logging the point in time when the script started.
*
* The `microtime()` function, when called without parameters, returns the current Unix timestamp
* as a string in microseconds formatted as "msec sec". This value is commonly used for precision
* timing calculations.
*/
define('START_TIME', microtime());
/**
* Constant BASE
*
* Defines the absolute path to the current directory,
* concatenated with the system-specific directory separator.
* This can be used for constructing file paths within the application.
*/
const BASE = __DIR__ . DIRECTORY_SEPARATOR;
/*
__ ___ ______ __
/ |/ /___ __ _____ _________ _ / ____/________ _____ ___ ___ _ ______ _____/ /__
/ /|_/ / __ `/ | / / _ \/ ___/ __ `/ / /_ / ___/ __ `/ __ `__ \/ _ \ | /| / / __ \/ ___/ //_/
/ / / / /_/ /| |/ / __/ / / /_/ / / __/ / / / /_/ / / / / / / __/ |/ |/ / /_/ / / / ,<
/_/ /_/\__,_/ |___/\___/_/ \__,_/ /_/ /_/ \__,_/_/ /_/ /_/\___/|__/|__/\____/_/ /_/|_|
Project : Mavera Framework
Author : Ahmet Tulgar
E-Mail : tulgar@outlook.com.tr
Year : 2023, 12
Version : v1.1
*/
if (isset($argv)) {
$_GET["q"] = $argv[1];
/**
* Constant BACKGROUND_PROCESS
*
* Indicates whether the application should consider operations being executed
* as part of a background or asynchronous process. When set to TRUE, this constant
* can be used to distinguish between foreground and background execution contexts
* and apply corresponding logic or configurations, such as reduced logging or resource prioritization.
*/
define("BACKGROUND_PROCESS", TRUE);
error_reporting(0);
}
/**
* DEBUG_SYSTEM is a constant used to toggle the debugging mode in the application.
* When set to TRUE, the system will display or log detailed debugging information that
* can help in diagnosing and resolving issues during development or troubleshooting.
* When set to FALSE, debugging information will be suppressed for a production environment.
*/
const DEBUG_SYSTEM = TRUE;
error_reporting(0);
include "System/Base/Framework/Bootstrap.php";