Files
XikaandPaperclip 7a6f91f7b6 fix(view): respect APP_URL and X-Forwarded-* headers in getBaseUrl()
When the app runs behind a reverse proxy (NPM), SERVER_PORT was 8080
(the backend port) causing asset URLs to include :8080 even though
clients access via HTTPS on port 443.

Priority: if APP_URL is set in the environment, use it directly.
Fallback: honour X-Forwarded-Proto and X-Forwarded-Port headers before
falling back to the raw SERVER vars.

Fixes crm-moneyflix.bitreport.pt asset URLs generating :8080 suffix.

Co-Authored-By: Paperclip <[email protected]>
2026-06-10 18:57:48 +00:00

332 lines
10 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Core;
/**
* View - Sistema de renderização de views com suporte a assets modulares
*/
class View
{
private static array $namespaces = [];
private static array $assets = [];
private static array $loadedModules = [];
/**
* Add a namespace for a views directory.
* @param string $namespace The namespace name (e.g., 'crm').
* @param string $path The path to the module's views directory.
*/
public static function addNamespace(string $namespace, string $path): void
{
self::$namespaces[$namespace] = rtrim($path, '/\\');
}
/**
* Renderizar uma view com suporte a assets modulares
*/
public static function render(string $view, array $data = []): void
{
// Initialize AssetManager if not already done
AssetManager::initialize();
// Auto-detect and load module assets based on view path
self::autoLoadModuleAssets($view);
// Extract data to variables
extract($data);
// Include module assets in head if rendering main layout
if (strpos($view, 'layouts/main.php') !== false) {
$data['module_css'] = self::getModuleCss();
$data['module_js'] = self::getModuleJs();
extract($data);
}
// Render the view
$viewPath = self::getViewPath($view);
if (!file_exists($viewPath)) {
throw new \Exception("View file not found: {$view}");
}
include $viewPath;
}
/**
* Auto-load module assets based on view path
*/
private static function autoLoadModuleAssets(string $view): void
{
$assetManager = AssetManager::getInstance();
// Get active modules from AssetManager
$activeModules = $assetManager->getActiveModules();
// Also detect modules from view path
if (strpos($view, '@') === 0) {
// Module-specific view (@modulename/view)
$parts = explode('/', substr($view, 1));
if (!empty($parts[0])) {
$moduleName = ucfirst($parts[0]);
if (!in_array($moduleName, $activeModules)) {
$activeModules[] = $moduleName;
}
}
}
// Load assets for active modules
foreach ($activeModules as $module) {
if (!in_array($module, self::$loadedModules)) {
self::$loadedModules[] = $module;
}
}
}
/**
* Get CSS links for loaded modules
*/
private static function getModuleCss(): string
{
$assetManager = AssetManager::getInstance();
return $assetManager->getCssLinks(self::$loadedModules);
}
/**
* Get JS scripts for loaded modules
*/
private static function getModuleJs(): string
{
$assetManager = AssetManager::getInstance();
return $assetManager->getJsScripts(self::$loadedModules);
}
/**
* Get view path
*/
private static function getViewPath(string $view): string
{
// Handle module-specific views (@modulename/view)
if (strpos($view, '@') === 0) {
$parts = explode('/', substr($view, 1), 2);
$namespace = $parts[0];
$viewFile = $parts[1] ?? 'index.php';
// Add .php extension if not present
if (substr($viewFile, -4) !== '.php') {
$viewFile .= '.php';
}
// Check if namespace is registered
if (isset(self::$namespaces[$namespace])) {
return self::$namespaces[$namespace] . '/' . $viewFile;
}
// Fallback to module path
return PathManager::getModulesPath() . '/' . ucfirst($namespace) . '/Views/' . $viewFile;
}
// Handle absolute paths (starting with /)
if (strpos($view, '/') === 0) {
// Add .php extension if not present
if (substr($view, -4) !== '.php') {
$view .= '.php';
}
return $view;
}
// Handle relative paths (starting with app/, modules/, etc.)
if (strpos($view, 'app/') === 0 || strpos($view, 'modules/') === 0) {
// Add .php extension if not present
if (substr($view, -4) !== '.php') {
$view .= '.php';
}
return PathManager::getRootPath() . '/' . $view;
}
// Regular views - look in multiple locations
$basePaths = [
PathManager::getAppPath() . '/Views',
PathManager::getRootPath() . '/Views',
PathManager::getRootPath() . '/app/Views'
];
// Add .php extension if not present
if (substr($view, -4) !== '.php') {
$view .= '.php';
}
// Try each base path
foreach ($basePaths as $basePath) {
$fullPath = $basePath . '/' . $view;
if (file_exists($fullPath)) {
return $fullPath;
}
}
// If not found, return the first possible path for error reporting
return $basePaths[0] . '/' . $view;
}
/**
* Register an asset to be loaded (renamed to avoid conflict)
*/
public static function registerAsset(string $asset): void
{
if (!in_array($asset, self::$assets)) {
self::$assets[] = $asset;
}
}
/**
* Get all registered assets
*/
public static function getAssets(): array
{
return self::$assets;
}
/**
* Render a component with its own assets
*/
public static function component(string $component, array $data = []): void
{
// Auto-load component-specific assets
$componentModule = self::getComponentModule($component);
if ($componentModule && !in_array($componentModule, self::$loadedModules)) {
self::$loadedModules[] = $componentModule;
}
self::render($component, $data);
}
/**
* Get module name from component path
*/
private static function getComponentModule(string $component): ?string
{
if (strpos($component, 'components/') === 0) {
$parts = explode('/', $component);
if (count($parts) >= 2) {
return ucfirst($parts[1]);
}
}
return null;
}
/**
* Compile and serve module SCSS assets
*/
public static function compileModuleAssets(): bool
{
$assetManager = AssetManager::getInstance();
return $assetManager->compileScssAssets();
}
/**
* Get debug information about loaded modules and assets
*/
public static function getDebugInfo(): array
{
$assetManager = AssetManager::getInstance();
return [
'loaded_modules' => self::$loadedModules,
'registered_assets' => self::$assets,
'discovered_assets' => $assetManager->getRegisteredAssets(),
'active_modules' => $assetManager->getActiveModules(),
];
}
/**
* Include a view partial. This is a simple include wrapper.
* @param string $path Path to the view file relative to app/Views
* @param array $params Parameters to pass to the view
*/
public static function include(string $path, array $params = []): void
{
$fullPath = self::getViewPath($path);
if (file_exists($fullPath)) {
extract($params);
include $fullPath;
} else {
error_log("Include file not found: " . $fullPath);
}
}
/**
* Get the full URL for an asset.
* @param string $path Asset path relative to public/assets
* @return string Full URL to the asset
*/
public static function asset(string $path): string
{
// Remove leading slash and ensure path starts with assets/
$path = ltrim($path, '/');
if (!str_starts_with($path, 'assets/')) {
$path = 'assets/' . $path;
}
return self::getBaseUrl() . '/' . $path;
}
/**
* Get the base URL for the application.
* @return string Base URL
*/
public static function getBaseUrl(): string
{
// Use explicit APP_URL when set (required for reverse-proxy deployments)
$appUrl = $_ENV['APP_URL'] ?? '';
if ($appUrl && filter_var($appUrl, FILTER_VALIDATE_URL)) {
return rtrim($appUrl, '/');
}
// Detect scheme: check X-Forwarded-Proto first (set by reverse proxy)
$forwardedProto = $_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '';
if ($forwardedProto === 'https') {
$protocol = 'https';
} else {
$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
}
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
// If HTTP_HOST already includes the port, use it as is
if (strpos($host, ':') !== false) {
return $protocol . '://' . $host;
}
// Use X-Forwarded-Port if available, otherwise fall back to SERVER_PORT
$port = $_SERVER['HTTP_X_FORWARDED_PORT'] ?? $_SERVER['SERVER_PORT'] ?? '';
$port = ($port === '80' || $port === '443') ? '' : ':' . $port;
return $protocol . '://' . $host . $port;
}
/**
* Render a view to a string instead of outputting directly.
* @param string $view View path
* @param array $data Data to pass to the view
* @return string Rendered view content
*/
public static function renderToString(string $view, array $data = []): string
{
ob_start();
self::render($view, $data);
return ob_get_clean();
}
/**
* Reset view state (for testing)
*/
public static function reset(): void
{
self::$namespaces = [];
self::$assets = [];
self::$loadedModules = [];
}
}