Passed
Branch main (8837c4)
by Sílvio
14:13
created

ConnectionFactory   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 25
c 1
b 0
f 0
dl 0
loc 45
rs 10
wmc 9

1 Method

Rating   Name   Duplication   Size   Complexity  
B createConnection() 0 35 9
1
<?php
2
3
namespace Silviooosilva\CacheerPhp\Core;
4
5
use PDO;
6
use PDOException;
7
use Silviooosilva\CacheerPhp\Enums\DatabaseDriver;
8
use Silviooosilva\CacheerPhp\Exceptions\ConnectionException;
9
10
/**
11
 * Class ConnectionFactory
12
 * @author Sílvio Silva <https://github.com/silviooosilva>
13
 * @package Silviooosilva\CacheerPhp
14
 */
15
class ConnectionFactory
16
{
17
18
    /**
19
     * Creates a new PDO instance based on the specified database configuration.
20
     *
21
     * @param array|null $database
22
     * @return PDO|null
23
     * @throws ConnectionException
24
     */
25
    public static function createConnection(?array $database = null): ?PDO
26
    {
27
        $connection = Connect::getConnection();
28
        $dbConf = $database ?? CACHEER_DATABASE_CONFIG[$connection->value];
29
30
        $driver = null;
31
        if (isset($dbConf['adapter'])) {
32
            $driver = DatabaseDriver::tryFrom($dbConf['adapter']);
33
        }
34
        if ($driver === null && isset($dbConf['driver'])) {
35
            $driver = DatabaseDriver::tryFrom($dbConf['driver']);
36
        }
37
        $driver ??= $connection;
38
39
        $dsnDriver = $driver->dsnName();
40
        $dbConf['driver'] = $dsnDriver;
41
42
        if ($driver === DatabaseDriver::SQLITE) {
43
            $dbName = $dbConf['dbname'];
44
            $dbDsn = $dsnDriver . ':' . $dbName;
45
        } else {
46
            $dbName = "{$dsnDriver}-{$dbConf['dbname']}@{$dbConf['host']}";
0 ignored issues
show
Unused Code introduced by
The assignment to $dbName is dead and can be removed.
Loading history...
47
            $dbDsn = "{$dsnDriver}:host={$dbConf['host']};dbname={$dbConf['dbname']};port={$dbConf['port']}";
48
        }
49
50
        try {
51
            $options = $dbConf['options'] ?? [];
52
            foreach ($options as $key => $value) {
53
                if (is_string($value) && defined($value)) {
54
                    $options[$key] = constant($value);
55
                }
56
            }
57
            return new PDO($dbDsn, $dbConf['username'] ?? null, $dbConf['passwd'] ?? null, $options);
58
        } catch (PDOException $exception) {
59
            throw ConnectionException::create($exception->getMessage(), $exception->getCode(), $exception->getPrevious());
60
        }
61
    }
62
}
63