Passed
Push — main ( bce8dd...f4f8ca )
by Sílvio
56s
created

MigrationManager::getMigrationQueries()   B

Complexity

Conditions 6
Paths 12

Size

Total Lines 56
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 28
c 0
b 0
f 0
nc 12
nop 2
dl 0
loc 56
rs 8.8497

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Silviooosilva\CacheerPhp\Core;
4
5
use PDO;
6
use PDOException;
7
8
/**
9
 * Class MigrationManager
10
 * @author Sílvio Silva <https://github.com/silviooosilva>
11
 * @package Silviooosilva\CacheerPhp
12
 */
13
class MigrationManager
14
{
15
    /**
16
     * Executes the migration process for the database.
17
     * 
18
     * @param PDO $connection
19
     * @return void
20
     */
21
    public static function migrate(PDO $connection, ?string $tableName = null): void
22
    {
23
        try {
24
            self::prepareDatabase($connection);
25
            $queries = self::getMigrationQueries($connection, $tableName);
26
            foreach ($queries as $query) {
27
                if (trim($query)) {
28
                    $connection->exec($query);
29
                }
30
            }
31
        } catch (PDOException $exception) {
32
            throw new PDOException($exception->getMessage(), $exception->getCode());
33
        }
34
    }
35
36
    /**
37
     * Prepares the database connection for migration.
38
     * 
39
     * @param PDO $connection
40
     * @return void
41
     */
42
    private static function prepareDatabase(PDO $connection): void
43
    {
44
        $driver = $connection->getAttribute(PDO::ATTR_DRIVER_NAME);
45
        if ($driver !== 'sqlite') {
46
            $dbname = CACHEER_DATABASE_CONFIG[Connect::getConnection()]['dbname'];
47
            $connection->exec("USE $dbname");
48
        }
49
    }
50
51
    /**
52
     * Generates the SQL queries needed for the migration based on the database driver.
53
     * 
54
     * @param PDO $connection
55
     * @return array
56
     */
57
    private static function getMigrationQueries(PDO $connection, ?string $tableName = null): array
58
    {
59
        $driver = $connection->getAttribute(PDO::ATTR_DRIVER_NAME);
60
        $createdAtDefault = ($driver === 'pgsql') ? 'DEFAULT NOW()' : 'DEFAULT CURRENT_TIMESTAMP';
61
        $table = $tableName ?: (defined('CACHEER_TABLE') ? CACHEER_TABLE : 'cacheer_table');
62
63
        if ($driver === 'sqlite') {
64
            $query = "
65
                CREATE TABLE IF NOT EXISTS {$table} (
66
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
67
                    cacheKey VARCHAR(255) NOT NULL,
68
                    cacheData TEXT NOT NULL,
69
                    cacheNamespace VARCHAR(255),
70
                    expirationTime DATETIME NOT NULL,
71
                    created_at DATETIME $createdAtDefault,
72
                    UNIQUE(cacheKey, cacheNamespace)
73
                );
74
                CREATE INDEX IF NOT EXISTS idx_{$table}_cacheKey ON {$table} (cacheKey);
75
                CREATE INDEX IF NOT EXISTS idx_{$table}_cacheNamespace ON {$table} (cacheNamespace);
76
                CREATE INDEX IF NOT EXISTS idx_{$table}_expirationTime ON {$table} (expirationTime);
77
                CREATE INDEX IF NOT EXISTS idx_{$table}_key_namespace ON {$table} (cacheKey, cacheNamespace);
78
            ";
79
        } elseif ($driver === 'pgsql') {
80
            $query = "
81
                CREATE TABLE IF NOT EXISTS {$table} (
82
                    id SERIAL PRIMARY KEY,
83
                    cacheKey VARCHAR(255) NOT NULL,
84
                    cacheData TEXT NOT NULL,
85
                    cacheNamespace VARCHAR(255),
86
                    expirationTime TIMESTAMP NOT NULL,
87
                    created_at TIMESTAMP $createdAtDefault,
88
                    UNIQUE(cacheKey, cacheNamespace)
89
                );
90
                CREATE INDEX IF NOT EXISTS idx_{$table}_cacheKey ON {$table} (cacheKey);
91
                CREATE INDEX IF NOT EXISTS idx_{$table}_cacheNamespace ON {$table} (cacheNamespace);
92
                CREATE INDEX IF NOT EXISTS idx_{$table}_expirationTime ON {$table} (expirationTime);
93
                CREATE INDEX IF NOT EXISTS idx_{$table}_key_namespace ON {$table} (cacheKey, cacheNamespace);
94
            ";
95
        } else {
96
            $query = "
97
                CREATE TABLE IF NOT EXISTS {$table} (
98
                    id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
99
                    cacheKey VARCHAR(255) NOT NULL,
100
                    cacheData LONGTEXT NOT NULL,
101
                    cacheNamespace VARCHAR(255) NULL,
102
                    expirationTime DATETIME NOT NULL,
103
                    created_at TIMESTAMP $createdAtDefault,
104
                    UNIQUE KEY unique_cache_key_namespace (cacheKey, cacheNamespace),
105
                    KEY idx_{$table}_cacheKey (cacheKey),
106
                    KEY idx_{$table}_cacheNamespace (cacheNamespace),
107
                    KEY idx_{$table}_expirationTime (expirationTime),
108
                    KEY idx_{$table}_key_namespace (cacheKey, cacheNamespace)
109
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
110
            ";
111
        }
112
        return array_filter(array_map('trim', explode(';', $query)));
113
    }
114
}
115