File: /home/storage/5/78/dd/wicomm2/public_html/blackfriday/lib/Utils.php
<?php
require_once __DIR__ . '/../config/config.php';
// Polyfill para PHP < 8
if (!function_exists('str_starts_with')) {
function str_starts_with($haystack, $needle) {
return $needle === '' ? true : strpos($haystack, $needle) === 0;
}
}
class Utils {
public static function boot(): void {
// timezone
$tz = defined('APP_TIMEZONE') ? APP_TIMEZONE : 'America/Sao_Paulo';
@date_default_timezone_set($tz);
// storage
if (defined('STORAGE_DIR') && !is_dir(STORAGE_DIR)) {
@mkdir(STORAGE_DIR, 0775, true);
}
// Handlers para garantir JSON até em erro fatal
self::installHandlers();
}
public static function installHandlers(): void {
// transforma notices/warnings em exceptions
set_error_handler(function ($severity, $message, $file, $line) {
if (!(error_reporting() & $severity)) return false;
throw new ErrorException($message, 0, $severity, $file, $line);
});
// captura excepcões não tratadas
set_exception_handler(function ($e) {
self::log('[EXCEPTION] '.$e->getMessage().' @ '.$e->getFile().':'.$e->getLine());
self::json(['ok'=>false, 'error'=>'fatal: '.$e->getMessage()], 500);
});
// captura erro fatal
register_shutdown_function(function () {
$err = error_get_last();
if ($err && in_array($err['type'], [E_ERROR,E_PARSE,E_CORE_ERROR,E_COMPILE_ERROR])) {
self::log('[SHUTDOWN] '.$err['message'].' @ '.$err['file'].':'.$err['line']);
// tenta responder JSON (caso algo já tenha sido enviado, pode não funcionar, mas tentamos)
if (!headers_sent()) {
http_response_code(500);
header('Content-Type: application/json; charset=utf-8');
}
echo json_encode([
'ok' => false,
'error' => 'fatal: '.$err['message'],
'file' => $err['file'],
'line' => $err['line']
], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
}
});
}
public static function json($data, int $code = 200): void {
if (!headers_sent()) {
http_response_code($code);
header('Content-Type: application/json; charset=utf-8');
}
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
public static function requirePostJSON(): array {
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
if (!is_array($data)) {
self::json(['ok'=>false,'error'=>'Invalid JSON body'], 400);
}
return $data;
}
public static function storagePath(string $filename = ''): string {
$base = defined('STORAGE_DIR') ? STORAGE_DIR : (__DIR__ . '/../storage');
if (!is_dir($base)) {
@mkdir($base, 0775, true);
}
return rtrim($base, '/').'/'.$filename;
}
public static function uuid(): string {
return bin2hex(random_bytes(16));
}
public static function log(string $msg): void {
$line = '['.date('c').'] '.$msg."\n";
@file_put_contents(self::storagePath('error.log'), $line, FILE_APPEND);
}
}