v1.0.0.1
StocketBase
- <?php
-
- declare(strict_types=1);
-
- final class AppVersion
- {
- private const FALLBACK = '0.0.0.0 Unknown';
-
- public static function fromFile(): ?string
- {
- $path = __DIR__ . '/../version.txt';
- if (!is_file($path)) {
- return null;
- }
-
- $value = trim((string) file_get_contents($path));
-
- return $value !== '' ? $value : null;
- }
-
- public static function current(?PDO $db = null): string
- {
- $fileVersion = self::fromFile();
-
- try {
- $db ??= Database::site();
- self::ensureTable($db);
-
- $row = $db->query('SELECT version FROM app_version WHERE id = 1')->fetch();
-
- if ($fileVersion !== null) {
- if (!$row) {
- $db->prepare('INSERT INTO app_version (id, version) VALUES (1, :version)')->execute(['version' => $fileVersion]);
- } elseif ($row['version'] !== $fileVersion) {
- $db->prepare('UPDATE app_version SET version = :version WHERE id = 1')->execute(['version' => $fileVersion]);
- }
-
- return $fileVersion;
- }
-
- if ($row && trim((string) $row['version']) !== '') {
- return (string) $row['version'];
- }
- } catch (Throwable $exception) {
- error_log('StocketBase: version table unavailable: ' . $exception->getMessage());
- }
-
- return $fileVersion ?? self::FALLBACK;
- }
-
- public static function numeric(string $version): string
- {
- return preg_match('/^\s*v?(\d+(?:\.\d+)*)/i', $version, $match) === 1 ? $match[1] : '0';
- }
-
- public static function compare(string $a, string $b): int
- {
- return version_compare(self::numeric($a), self::numeric($b));
- }
-
- private static function ensureTable(PDO $db): void
- {
- $db->exec(
- 'CREATE TABLE IF NOT EXISTS app_version (
- id TINYINT UNSIGNED NOT NULL PRIMARY KEY,
- version VARCHAR(60) NOT NULL,
- updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci'
- );
- }
- }
-