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

Connect::__clone()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 1
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 0
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 1
rs 10
1
<?php
2
3
namespace Silviooosilva\CacheerPhp\Core;
4
5
use Exception;
6
use PDO;
7
use PDOException;
8
9
/**
10
 * Class Connect
11
 * @author Sílvio Silva <https://github.com/silviooosilva>
12
 * @package Silviooosilva\CacheerPhp
13
 */
14
class Connect
15
{
16
17
    /**
18
     * @var string
19
     */
20
    public static string $connection = 'sqlite';
21
22
    /**
23
     * @var array
24
     */
25
    private static array $instance;
26
27
    /**
28
     * @var PDOException|null
29
     */
30
    private static ?PDOException $error = null;
31
32
    /**
33
     * @param array|null $database
34
     * @return PDO|null
35
     */
36
    public static function getInstance(array $database = null)
37
    {
38
        $dbConf = $database ?? CACHEER_DATABASE_CONFIG[self::getConnection()];
39
40
        if ($dbConf["driver"] === 'sqlite') {
41
            $dbName = $dbConf["dbname"];
42
            $dbDsn = $dbConf["driver"] . ":" . $dbName;
43
        } else {
44
            $dbName = "{$dbConf["driver"]}-{$dbConf["dbname"]}@{$dbConf["host"]}";
45
            $dbDsn = $dbConf["driver"] . ":host=" . $dbConf["host"] . ";dbname=" . $dbConf["dbname"] . ";port=" . $dbConf["port"];
46
        }
47
48
        if (!isset(self::$instance)) {
49
            self::$instance = [];
50
        }
51
52
        if (empty(self::$instance[$dbName])) {
53
            try {
54
                $options = $dbConf["options"] ?? [];
55
                foreach ($options as $key => $value) {
56
                    if (is_string($value) && defined($value)) {
57
                        $options[$key] = constant($value);
58
                    }
59
                }
60
                self::$instance[$dbName] = new PDO(
61
                    $dbDsn,
62
                    $dbConf["username"] ?? null,
63
                    $dbConf["passwd"] ?? null,
64
                    $options
65
                );
66
                self::migrate(self::$instance[$dbName]);
67
            } catch (PDOException $exception) {
68
                self::$error = $exception;
69
                return null;
70
            }
71
        }
72
        return self::$instance[$dbName];
73
    }
74
75
    /**
76
     * @return void
77
     */
78
    public static function migrate(PDO $Connection)
79
    {
80
        $driver = $Connection->getAttribute(PDO::ATTR_DRIVER_NAME);
81
        $createdAtDefault = ($driver === 'pgsql') ? 'DEFAULT NOW()' : 'DEFAULT CURRENT_TIMESTAMP';
82
83
        try {
84
            if ($driver !== 'sqlite') {
85
                $Connection->exec("USE " . CACHEER_DATABASE_CONFIG[self::getConnection()]['dbname']);
86
            }
87
           
88
            if ($driver === 'sqlite') {
89
                $query = "CREATE TABLE IF NOT EXISTS cacheer_table (
90
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
91
                    cacheKey VARCHAR(255) NOT NULL,
92
                    cacheData TEXT NOT NULL,
93
                    cacheNamespace VARCHAR(255),
94
                    expirationTime DATETIME NOT NULL,
95
                    created_at DATETIME $createdAtDefault
96
                )";
97
            } else {
98
                $query = "CREATE TABLE IF NOT EXISTS cacheer_table (
99
                    id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
100
                    cacheKey VARCHAR(255) NOT NULL,
101
                    cacheData LONGTEXT NOT NULL,
102
                    cacheNamespace VARCHAR(255) NULL,
103
                    expirationTime DATETIME NOT NULL,
104
                    created_at TIMESTAMP $createdAtDefault
105
                )";
106
            }
107
            $Connection->exec($query);
108
        } catch (PDOException $exception) {
109
            self::$error = $exception;
110
        }
111
    }
112
113
    /**
114
     * @param string $connection
115
     * @throws \Exception
116
     * @return void
117
     */
118
    public static function setConnection(string $connection)
119
    {
120
        $drivers = ['mysql', 'sqlite', 'pgsql'];
121
        if (!in_array($connection, $drivers)) {
122
            throw new Exception("Only ['MySQL(mysql)', 'SQLite(sqlite)', 'PgSQL(pgsql)'] Are available at the moment...");
123
        }
124
        self::$connection = $connection;
125
    }
126
127
    /**
128
     * @return string
129
     */
130
    public static function getConnection()
131
    {
132
        return self::$connection;
133
    }
134
135
    /**
136
     * @return PDOException|null
137
     */
138
    public static function getError()
139
    {
140
        return self::$error;
141
    }
142
143
    /**
144
     * Connect constructor.
145
     */
146
    private function __construct() {}
147
148
    /**
149
     * Connect clone.
150
     */
151
    private function __clone() {}
152
}
153