Passed
Push — main ( a54930...73027a )
by Sílvio
13:04
created

SqliteHelper::createDatabaseFile()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 4
rs 10
1
<?php
2
3
namespace Silviooosilva\CacheerPhp\Helpers;
4
use Silviooosilva\CacheerPhp\Helpers\EnvHelper;
5
6
class SqliteHelper
7
{
8
9
    /**
10
     * @param string $database
11
     * @param string $path
12
     * @return string
13
     */
14
    public static function database(string $database = 'database.sqlite', string $path = null)
15
    {
16
        return self::getDynamicSqliteDbPath($database, $path);
17
    }
18
19
    /**
20
     * @return string
21
     */
22
    private static function getDynamicSqliteDbPath(string $database, string $path = null)
23
    {
24
        $rootPath = EnvHelper::getRootPath();
25
        $databaseDir = is_null($path) ? $rootPath . '/database' : $rootPath . '/' . $path;
26
        $dbFile = $databaseDir . '/' . self::checkExtension($database);
27
        
28
        if (!is_dir($databaseDir)) {
29
            self::createDatabaseDir($databaseDir);
30
        }
31
        if (!file_exists($dbFile)) {
32
            self::createDatabaseFile($dbFile);
33
        }
34
        
35
        return $dbFile;
36
    }
37
38
    /**
39
    * @param string $databaseDir
40
    * @return void
41
    */
42
    private static function createDatabaseDir(string $databaseDir)
43
    {
44
        if (!is_dir($databaseDir)) {
45
            mkdir($databaseDir, 0755, true);
46
        }
47
    }
48
49
    /**
50
    * @param string $dbFile
51
    * @return void
52
    */
53
    private static function createDatabaseFile(string $dbFile)
54
    {
55
        if (!file_exists($dbFile)) {
56
            file_put_contents($dbFile, '');
57
        }
58
    }
59
60
    /**
61
    * @param string $database
62
    * @return string
63
    */
64
    private static function checkExtension(string $database)
65
    {
66
        if (strpos($database, '.sqlite') === false) {
67
            return $database . '.sqlite';
68
        }
69
        return $database;
70
    }
71
72
}
73