'Y']); * * Nei cron (senza sessione) passare l'idschool esplicito: * SchoolSettings::get('show_teacher', 'N', $idschool); */ if (!class_exists('DBHandlerSelect')) { require_once __DIR__ . '/db-functions.php'; } class SchoolSettings { /** @var array cache per scuola: idschool => riga option */ private static $cache = []; /** Colonne che non si possono modificare con save() */ const PROTECTED_COLUMNS = ['idption', 'idschool']; /** Tutte le impostazioni della scuola (riga creata se mancante) */ public static function all(?int $idschool = null): array { $idschool = self::schoolId($idschool); if (!isset(self::$cache[$idschool])) { $pdo = self::pdo(); $st = $pdo->prepare("SELECT * FROM `option` WHERE idschool = ? LIMIT 1"); $st->execute([$idschool]); $row = $st->fetch(); if (!$row) { // Nuova scuola: crea la riga con i default delle colonne try { $pdo->prepare("INSERT INTO `option` (idschool) VALUES (?)")->execute([$idschool]); $st->execute([$idschool]); $row = $st->fetch(); } catch (PDOException $e) { error_log('SchoolSettings: impossibile creare option per scuola ' . $idschool . ': ' . $e->getMessage()); $row = []; } } self::$cache[$idschool] = $row ?: []; } return self::$cache[$idschool]; } /** Singola impostazione, con default se mancante o NULL */ public static function get(string $key, $default = null, ?int $idschool = null) { $all = self::all($idschool); return (array_key_exists($key, $all) && $all[$key] !== null) ? $all[$key] : $default; } /** * Salva una o più impostazioni. Accetta solo colonne esistenti in `option` * (le altre chiavi vengono ignorate). */ public static function save(array $data, ?int $idschool = null): void { $idschool = self::schoolId($idschool); $current = self::all($idschool); $set = []; $params = []; foreach ($data as $col => $val) { if (!array_key_exists($col, $current) || in_array($col, self::PROTECTED_COLUMNS, true)) { continue; } $set[] = "`$col` = ?"; $params[] = $val; } if (empty($set)) { return; } $params[] = $idschool; self::pdo()->prepare("UPDATE `option` SET " . implode(', ', $set) . " WHERE idschool = ?") ->execute($params); unset(self::$cache[$idschool]); } private static function schoolId(?int $idschool): int { if ($idschool !== null && $idschool > 0) { return $idschool; } return SchoolContext::id(); } private static function pdo(): PDO { return DBHandlerSelect::getInstance()->getConnection(); } }