# Bootstrap

The `Bootstrap` class in the Bootstrap.php file is a core component of the framework, responsible for initializing and configuring the application. It handles the setup of essential configurations, routing, and middleware processing. Below is an overview of its key functionalities:

## Namespace and Imports

```php
?php
namespace System\Core;
use System\Libraries\Logger;
use Exception;

if (!defined('ROOT_PATH')) {
    exit('No direct access allowed.');
}

require_once ROOT_PATH . '/system/Helpers/Core_helper.php';
load_helpers(['uri', 'security']);
```

* Defines the namespace `System\Core`.
* Imports the `Logger` class and the `Exception` class.
* Checks if `ROOT_PATH` is defined. If not, it prevents direct access to the file.
* Loads the `Core_helper.php` file to use the `load_helpers` function.
* Loads the `uri` and `security` helpers.

## Class Definition

```php
<?php
class Bootstrap {

    protected $routes;
    protected $uri;

    public function __construct() {
        $appConfig = config('app');
        if (!empty($appConfig['app_timezone'])) {
            date_default_timezone_set($appConfig['app_timezone']);
        }
        if (!empty($appConfig['debug']) && $appConfig['debug']) {
            ini_set('display_startup_errors', 1);
            ini_set('display_errors', 1);
            error_reporting(-1);
        } else {
            ini_set('display_startup_errors', 0);
            ini_set('display_errors', 0);
            error_reporting(E_ALL & ~E_NOTICE);
        }
        $this->init_uri();
        $this->routes = new Router(); // Create an instance for Router
        $this->loadRoutes();          // Load the routes
    }
}
```

* Defines the `Bootstrap` class with protected properties `$routes` and `$uri`.
* The constructor sets the timezone, configures error reporting based on the debug mode, initializes the URI, creates a `Router` instance, and loads the routes.

## `init_uri()`

```php
private function init_uri() {
    $originalUri = request_uri();
    $originalQ = $_SERVER['QUERY_STRING'] ?? '';
    $uri = uri_security($originalUri);
    $sanitizedQueryString = '';
    
    if (!empty($originalQ)) {
        $safeGet = sget_security(); 
        $sanitizedQueryString = http_build_query($safeGet); 
    }
    
    $cleanFull = '/' . trim($uri, '/') . '/';  "
    if ($sanitizedQueryString !== '') {
        $cleanFull .= '?' . $sanitizedQueryString;
    }
    
    $cleanFull = '/' . ltrim($cleanFull, '/');
    if ($cleanFull !== $_SERVER['REQUEST_URI'] && $cleanFull !== $_SERVER['REQUEST_URI'] . '/') {
        redirect(base_url($cleanFull));
    }
    
    unset($safeGet, $sanitizedQueryString, $originalUri, $cleanFull);
 
    $this->uri = [
        'uri' => $uri,
        'split' => explode('/', $uri)
    ];
    unset($uri);
    if (!empty($this->uri['split'][0]) && in_array($this->uri['split'][0], LANG_LIST)) {
        array_shift($this->uri['split']); 
        $this->uri['uri'] = implode('/', $this->uri['split']);
    }
    return $this->uri;
}
```

* Initializes the URI by sanitizing it and redirecting if necessary.
* Splits the URI into parts and handles language prefixes.

## `run()`

```php
public function run() {
        try {
            if (!isset($_SERVER['REQUEST_METHOD'])) $_SERVER['REQUEST_METHOD'] = 'GET';
            $method = $_SERVER['REQUEST_METHOD'];
            $this->dispatch($this->uri['uri'], $method);
        } catch (AppException $e) {
            $e->handle();
        } catch (\Throwable $e) { // Catch all exceptions and errors
            Logger::error($e->getMessage(), $e->getFile(), $e->getLine());
            http_response_code(500);
            if (!empty(config('app')['debug'])) {
                echo $e->getMessage(), $e->getFile(), $e->getLine();
            } else {
                echo "An unknown error has occurred. Lets check file logger.log!";
            }
        }
    }
```

* Runs the framework.
* Checks the HTTP method of the request (GET, POST, etc.).
* Calls the `dispatch()` method to route the URI to the corresponding controller and action.
* Catches and handles `AppException` and other errors, logs the error, and displays an error message.

## `loadRoutes()`

```php
 private function loadRoutes() {
        global $routes;
        $routes = $this->routes;
        if (!empty($this->uri) && !empty($this->uri['split']) && $this->uri['split'][0] == 'api') {
            if (file_exists(ROOT_PATH . '/application/Routes/Api.php')) {
                require_once ROOT_PATH . '/application/Routes/Api.php';
            }
        }
        if (file_exists(ROOT_PATH . '/application/Routes/Web.php')) {
            require_once ROOT_PATH . '/application/Routes/Web.php';
        }
    }
```

* Loads the routes from the `Api.php` and `Web.php` route files.
* Uses the global `$routes` variable to store the routes.
* Checks and loads the corresponding route files if they exist.

## `dispatch()`

```php
private function dispatch($uri, $method) {
        $route = $this->routes->match($uri, $method);
        if (isset($route['action']) && $route['action'][0] == '_') {
            throw new AppException("404 - Router: /{$uri} ({$method}) can not access!", 404, null, 404);
        }
        
        if (!$route) {
            throw new AppException("404 - Router: /{$uri} ({$method}) not found!", 404, null, 404);
        }
        
        $middleware = new Middleware();
        if (!empty($route['middleware'])) {
            foreach ($route['middleware'] as $mw) {
                $middleware->add($mw);
            }
        }

      
        unset($route['middleware']);
        $route['uri'] = $uri;
        $middleware->handle($route, function () use ($route) {
            $controllerClass = $route['controller'];
            $action = $route['action'];
            $params = $route['params'];
            
            if (!class_exists($controllerClass)) {
                throw new AppException("Controller {$controllerClass} not found.", 404, null, 404);
            }
            
            $controller = new $controllerClass();

            if (!method_exists($controller, $action)) {
                throw new AppException("Action {$action} not found in {$controllerClass} Controller.", 404, null, 404);
            }

            call_user_func_array([$controller, $action], $params);
        });
    }
```

* Routes the URI to the corresponding controller and action.
* Uses `Router` to match the URI and HTTP method with the corresponding route.
* Checks and handles middleware before calling the controller.
* Checks the existence of the controller and action, throws an exception if not found.
* Calls the controller and action with the corresponding parameters.

{% hint style="success" %}
Conclusion

The methods in `Bootstrap.php` help initialize and route the framework, handle the URI, load the routes, and route the request to the corresponding controller and action. These methods also handle exceptions and log errors to ensure the application runs smoothly.
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.cmsfullform.com/documents/core/bootstrap.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
