Completed
Push — master ( 229d9d...1c9390 )
by Alberto
01:52
created

Db::connect()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 1 Features 2
Metric Value
c 6
b 1
f 2
dl 0
loc 9
rs 9.6666
cc 2
eloc 6
nc 2
nop 1
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 - 2016  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 array
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
     * @param bool   $force    forzar nueva conexion PDO
48
     *
49
     * @return PDO
50
     * @throw KumbiaException
51
     */
52
    public static function get($database = 'default', $force = false)
53
    {
54
        // Verifica el singleton
55
        if (!$force && isset(self::$pool[$database])) {
56
            return self::$pool[$database];
57
        }
58
59
        if ($force) {
60
            return self::connect(self::getConfig($database));
61
        }
62
63
        return self::$pool[$database] = self::connect(self::getConfig($database));
64
    }
65
66
    /**
67
     * Conexión a la base de datos.
68
     *
69
     * @param array $config Config base de datos a conectar
70
     *
71
     * @return PDO
72
     */
73
    private static function connect($config)
74
    {
75
        try {
76
            return new PDO($config['dsn'], $config['username'], $config['password'], $config['params']);
77
        } catch (\PDOException $e) { //TODO: comprobar
78
                $message = $e->getMessage();
79
            throw new \RuntimeException("No se pudo realizar la conexión con '{$config['dsn']}'. {$message}");
80
        }
81
    }
82
83
    /**
84
     * Obtiene manejador de conexión a la base de datos.
85
     *
86
     * @param string $database base de datos a conectar
87
     *
88
     * @return array
89
     */
90
    private static function getConfig($database)
91
    {
92
        if (empty(self::$config)) {
93
            // Leer la configuración de conexión
94
            self::$config = require APP_PATH.'config/databases.php';
95
        }
96
        if (!isset(self::$config[$database])) {
97
            throw new \RuntimeException("No existen datos de conexión para la bd '$database' en ".APP_PATH.'config/databases.php');
98
        }
99
100
            // Envia y carga los valores por defecto para la conexión, si no existen
101
        return self::$config[$database] +  [
102
                'dns'      => null,
103
                'username' => null,
104
                'password' => null,
105
                'params'   => [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION],
106
            ];
107
    }
108
109
    /**
110
     * Permite agregar una base de datos sin leer del archivo de configuracion.
111
     *
112
     * @param array $value Valores de la configuración
113
     */
114
    public static function setConfig(array $value)
115
    {
116
        self::$config = [] +  self::$config + $value;
117
    }
118
}
119