File: /var/www/crmfidelity/bootstrap.php
<?php
declare(strict_types=1);
/**
* Bootstrap dell'applicazione.
* Carica config, autoloader, error handler, DB, sessione, helpers.
*/
// 1. PSR-4 autoloader minimale (App\* -> /app/*)
spl_autoload_register(function (string $class): void {
$prefix = 'App\\';
if (!str_starts_with($class, $prefix)) return;
$relative = substr($class, strlen($prefix));
$file = __DIR__ . '/app/' . str_replace('\\', '/', $relative) . '.php';
if (is_file($file)) {
require $file;
}
});
// 2. Carica configurazione
$config = require __DIR__ . '/config/config.php';
date_default_timezone_set($config['app']['timezone']);
// 3. Error handler
if ($config['app']['debug']) {
error_reporting(E_ALL);
ini_set('display_errors', '1');
} else {
error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');
ini_set('error_log', $config['storage']['path'] . '/logs/php-error.log');
}
set_exception_handler(function (\Throwable $e) use ($config): void {
$logFile = $config['storage']['path'] . '/logs/app.log';
$msg = sprintf(
"[%s] %s: %s in %s:%d\n%s\n\n",
date('Y-m-d H:i:s'),
get_class($e),
$e->getMessage(),
$e->getFile(),
$e->getLine(),
$e->getTraceAsString()
);
@file_put_contents($logFile, $msg, FILE_APPEND);
if (PHP_SAPI === 'cli') {
fwrite(STDERR, $msg);
exit(1);
}
http_response_code(500);
if (str_contains($_SERVER['REQUEST_URI'] ?? '', '/api/')) {
header('Content-Type: application/json; charset=utf-8');
echo json_encode([
'error' => 'server_error',
'message' => $config['app']['debug'] ? $e->getMessage() : 'Errore interno',
]);
} else {
header('Content-Type: text/html; charset=utf-8');
echo '<h1>Errore 500</h1>';
if ($config['app']['debug']) {
echo '<pre>' . htmlspecialchars($msg) . '</pre>';
}
}
});
// 4. Bootstrap servizi
\App\Core\Database::boot($config['db']);
\App\Core\Config::set($config);
// 5. Sessione (solo per richieste web, non CLI/API stateless)
if (PHP_SAPI !== 'cli' && !str_contains($_SERVER['REQUEST_URI'] ?? '', '/api/')) {
$sess = $config['session'];
session_name($sess['name']);
session_set_cookie_params([
'lifetime' => $sess['lifetime'] * 60,
'path' => '/',
'secure' => $sess['secure'],
'httponly' => true,
'samesite' => $sess['samesite'],
]);
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
}