1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Silviooosilva\CacheerPhp\Helpers; |
4
|
|
|
use Silviooosilva\CacheerPhp\Helpers\EnvHelper; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* Class SqliteHelper |
8
|
|
|
* @author Sílvio Silva <https://github.com/silviooosilva> |
9
|
|
|
* @package Silviooosilva\CacheerPhp |
10
|
|
|
*/ |
11
|
|
|
class SqliteHelper |
12
|
|
|
{ |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Gets the path to the SQLite database file. |
16
|
|
|
* |
17
|
|
|
* @param string $database |
18
|
|
|
* @param ?string $path |
19
|
|
|
* @return string |
20
|
|
|
*/ |
21
|
|
|
public static function database(string $database = 'database.sqlite', ?string $path = null): string |
22
|
|
|
{ |
23
|
|
|
return self::getDynamicSqliteDbPath($database, $path); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Gets the path to the SQLite database file dynamically. |
28
|
|
|
* |
29
|
|
|
* @param string $database |
30
|
|
|
* @param ?string $path |
31
|
|
|
* @return string |
32
|
|
|
*/ |
33
|
|
|
private static function getDynamicSqliteDbPath(string $database, ?string $path = null): string |
34
|
|
|
{ |
35
|
|
|
$rootPath = EnvHelper::getRootPath(); |
36
|
|
|
$databaseDir = is_null($path) ? $rootPath . '/database' : $rootPath . '/' . $path; |
37
|
|
|
$dbFile = $databaseDir . '/' . self::checkExtension($database); |
38
|
|
|
|
39
|
|
|
if (!is_dir($databaseDir)) { |
40
|
|
|
self::createDatabaseDir($databaseDir); |
41
|
|
|
} |
42
|
|
|
if (!file_exists($dbFile)) { |
43
|
|
|
self::createDatabaseFile($dbFile); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
return $dbFile; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Creates the database directory if it does not exist. |
51
|
|
|
* |
52
|
|
|
* @param string $databaseDir |
53
|
|
|
* @return void |
54
|
|
|
*/ |
55
|
|
|
private static function createDatabaseDir(string $databaseDir): void |
56
|
|
|
{ |
57
|
|
|
if (!is_dir($databaseDir)) { |
58
|
|
|
mkdir($databaseDir, 0755, true); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* Creates the SQLite database file if it does not exist. |
64
|
|
|
* |
65
|
|
|
* @param string $dbFile |
66
|
|
|
* @return void |
67
|
|
|
*/ |
68
|
|
|
private static function createDatabaseFile(string $dbFile): void |
69
|
|
|
{ |
70
|
|
|
if (!file_exists($dbFile)) { |
71
|
|
|
file_put_contents($dbFile, ''); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* Checks if the database name has the correct extension. |
77
|
|
|
* If not, appends '.sqlite' to the name. |
78
|
|
|
* |
79
|
|
|
* @param string $database |
80
|
|
|
* @return string |
81
|
|
|
*/ |
82
|
|
|
private static function checkExtension(string $database): string |
83
|
|
|
{ |
84
|
|
|
if (!str_contains($database, '.sqlite')) { |
85
|
|
|
return $database . '.sqlite'; |
86
|
|
|
} |
87
|
|
|
return $database; |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
} |
91
|
|
|
|