WebOrbiton
v1.0.0.1

StocketBase

72 lines · 2.2 KB
  1. <?php
  2. ​
  3. declare(strict_types=1);
  4. ​
  5. final class AppVersion
  6. {
  7. private const FALLBACK = '0.0.0.0 Unknown';
  8. ​
  9. public static function fromFile(): ?string
  10. {
  11. $path = __DIR__ . '/../version.txt';
  12. if (!is_file($path)) {
  13. return null;
  14. }
  15. ​
  16. $value = trim((string) file_get_contents($path));
  17. ​
  18. return $value !== '' ? $value : null;
  19. }
  20. ​
  21. public static function current(?PDO $db = null): string
  22. {
  23. $fileVersion = self::fromFile();
  24. ​
  25. try {
  26. $db ??= Database::site();
  27. self::ensureTable($db);
  28. ​
  29. $row = $db->query('SELECT version FROM app_version WHERE id = 1')->fetch();
  30. ​
  31. if ($fileVersion !== null) {
  32. if (!$row) {
  33. $db->prepare('INSERT INTO app_version (id, version) VALUES (1, :version)')->execute(['version' => $fileVersion]);
  34. } elseif ($row['version'] !== $fileVersion) {
  35. $db->prepare('UPDATE app_version SET version = :version WHERE id = 1')->execute(['version' => $fileVersion]);
  36. }
  37. ​
  38. return $fileVersion;
  39. }
  40. ​
  41. if ($row && trim((string) $row['version']) !== '') {
  42. return (string) $row['version'];
  43. }
  44. } catch (Throwable $exception) {
  45. error_log('StocketBase: version table unavailable: ' . $exception->getMessage());
  46. }
  47. ​
  48. return $fileVersion ?? self::FALLBACK;
  49. }
  50. ​
  51. public static function numeric(string $version): string
  52. {
  53. return preg_match('/^\s*v?(\d+(?:\.\d+)*)/i', $version, $match) === 1 ? $match[1] : '0';
  54. }
  55. ​
  56. public static function compare(string $a, string $b): int
  57. {
  58. return version_compare(self::numeric($a), self::numeric($b));
  59. }
  60. ​
  61. private static function ensureTable(PDO $db): void
  62. {
  63. $db->exec(
  64. 'CREATE TABLE IF NOT EXISTS app_version (
  65. id TINYINT UNSIGNED NOT NULL PRIMARY KEY,
  66. version VARCHAR(60) NOT NULL,
  67. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
  68. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci'
  69. );
  70. }
  71. }
  72. ​