WizdomWeb/app/Core/View.php

61 lines
2.2 KiB
PHP

<?php
namespace WizdomNetworks\WizeWeb\Core;
use WizdomNetworks\WizeWeb\Utils\Logger;
use WizdomNetworks\WizeWeb\Utils\ErrorHandler;
use Exception;
/**
* View Renderer (v2)
*
* Handles view rendering, ensuring proper data passing, logging, and error handling.
*
* ## Features:
* - Dynamically resolves and includes view files.
* - Implements logging to track successful and failed rendering attempts.
* - Implements error handling to prevent fatal crashes.
*
* ## Methods:
* - `render(string $view, array $data = [])` - Renders the specified view file.
*/
class View
{
/**
* Renders a view file and passes data to it.
*
* @param string $view The name of the view file (relative to /resources/views/).
* @param array $data Associative array of variables to pass to the view.
* @throws Exception If the view file is not found.
*/
public static function render(string $view, array $data = []): void
{
try {
Logger::info("View::render() - Attempting to render: " . $view);
// Extract data to make variables available in the view
extract($data);
// Build the full path to the view file
$viewPath = realpath(__DIR__ . "/../../resources/views/" . str_replace('.', '/', $view) . ".php");
// Debugging: Log resolved path
Logger::info("View::render() - Resolved view path: " . ($viewPath ?: 'null'));
// Validate and include the view file
if ($viewPath && file_exists($viewPath)) {
include $viewPath;
Logger::info("View::render() - Successfully rendered: " . $view);
} else {
Logger::error("View::render() - View file not found: " . $view . " | Resolved path: " . ($viewPath ?: 'null'));
throw new Exception("View file not found: " . $view);
}
} catch (Exception $e) {
ErrorHandler::exception($e);
Logger::error("View::render() - Error rendering view '$view': " . $e->getMessage());
http_response_code(500);
echo "An internal error occurred. Please check the logs.";
}
}
}