Db::connect()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
1
<?php
2
/**
3
 * KumbiaPHP web & app Framework.
4
 *
5
 * LICENSE
6
 *
7
 * This source file is subject to the new BSD license that is bundled
8
 * with this package in the file LICENSE.txt.
9
 * It is also available through the world-wide-web at this URL:
10
 * http://wiki.kumbiaphp.com/Licencia
11
 * If you did not receive a copy of the license and are unable to
12
 * obtain it through the world-wide-web, please send an email
13
 * to [email protected] so we can send you a copy immediately.
14
 *
15
 * @category   Kumbia
16
 *
17
 * @copyright  2005 - 2020  Kumbia Team (http://www.kumbiaphp.com)
18
 * @license    http://wiki.kumbiaphp.com/Licencia     New BSD License
19
 */
20
namespace Kumbia\ActiveRecord;
21
22
use \PDO;
23
24
/**
25
 * Manejador de conexiones de base de datos.
26
 */
27
abstract class Db
28
{
29
    /**
30
     * Pool de conexiones.
31
     *
32
     * @var PDO[]
33
     */
34
    private static $pool = [];
35
36
    /**
37
     * Config de conexiones.
38
     *
39
     * @var array
40
     */
41
    private static $config = [];
42
43
    /**
44
     * Obtiene manejador de conexión a la base de datos.
45
     *
46
     * @param  string $database base de datos a conectar
47
     * 
48
     * @return PDO
49
     */
50
    public static function get(string $database = 'default'): PDO
51
    {
52
        return self::$pool[$database] ?? self::$pool[$database] = self::connect(self::getConfig($database));
53
    }
54
55
    /**
56
     * Conexión a la base de datos.
57
     *
58
     * @param  array               $config Config base de datos a conectar
59
     * 
60
     * @throws \RuntimeException
61
     * @return PDO
62
     */
63
    private static function connect(array $config): PDO
64
    {
65
        try {
66
            return new PDO($config['dsn'], $config['username'], $config['password'], $config['params']);
67
        } catch (\PDOException $e) {
68
            //TODO: comprobar
69
            $message = $e->getMessage();
70
            throw new \RuntimeException("No se pudo realizar la conexión con '{$config['dsn']}'. {$message}");
71
        }
72
    }
73
74
    /**
75
     * Obtiene manejador de conexión a la base de datos.
76
     *
77
     * @param  string              $database base de datos a conectar
78
     * 
79
     * @throws \RuntimeException
80
     * @return array
81
     */
82
    private static function getConfig(string $database): array
83
    {
84
        if (empty(self::$config)) {
85
            // Leer la configuración de conexión
86
            self::$config = require \APP_PATH.'config/databases.php';
87
        }
88
        if ( ! isset(self::$config[$database])) {
89
            throw new \RuntimeException("No existen datos de conexión para la bd '$database' en ".\APP_PATH.'config/databases.php');
90
        }
91
92
        // Envia y carga los valores por defecto para la conexión, si no existen
93
94
        return self::$config[$database] + [
95
            'dns'      => \null,
96
            'username' => \null,
97
            'password' => \null,
98
            'params'   => [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]
99
        ];
100
    }
101
102
    /**
103
     * Permite agregar una base de datos sin leer del archivo de configuracion.
104
     *
105
     * @param array $value Valores de la configuración
106
     */
107
    public static function setConfig(array $value)
108
    {
109
        self::$config = [] + self::$config + $value; //TODO retornar PDO
110
    }
111
}
112