<?php
 class vB_dB_Logger { use vB_Trait_NoSerialize; private bool $enabled; private string $context = ''; private string $file; private bool $isfile; private mixed $filepointer; private bool $initialized = false; public static function getDefault() : static { $config = vB::getConfig(); $request = vB::getRequest(); return new static( $config['Misc']['debug_sql'] ?? false, $config['Misc']['debug_sql_file'] ?? '', ($request ? $request->getVbUrlClean() : '') ); } public function __construct(bool $enabled, string $file, string $context) { $this->enabled = $enabled; $this->file = $file; $this->isfile = boolval($this->file); if ($this->isfile) { $this->context = $context; } } public function log(string $query, bool $force = false) : void { if (!$this->enabled AND !$force) { return; } $this->initLogFile(); $this->logMessage('Sql: ', $query); } public function logMessage(string $prefix, string $message) : void { if ($this->isfile) { if (isset($this->filepointer) AND flock($this->filepointer, LOCK_EX)) { fwrite($this->filepointer, $prefix); fwrite($this->filepointer, $message); fwrite($this->filepointer, "\n"); fflush($this->filepointer); flock($this->filepointer, LOCK_UN); } } else { echo $prefix, $message, "\n"; } } private function initLogFile() { if ($this->initialized) { return; } $this->initialized = true; if ($this->isfile) { try { $this->filepointer = $this->getFilePointer($this->file); $this->logMessage('Context: ', $this->context); $this->context = ''; } catch (Exception $e) { $this->enabled = false; $this->filepointer = null; } } } private function getFilePointer(string $file) : mixed { if (!file_exists($file)) { throw new Exception('Failed to open log file'); } if (is_dir($file)) { $file = $file . '/' . uniqid('sql_') . '.txt'; } $pointer = fopen($file, 'a'); if (!$pointer) { throw new Exception('Failed to open log file'); } return $pointer; } public function __destruct() { if (isset($this->filepointer)) { fclose($this->filepointer); } } } 