Db   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 93
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 93
rs 10
c 0
b 0
f 0
wmc 10
lcom 1
cbo 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A get() 0 13 4
A connect() 0 10 2
A getConfig() 0 19 3
A setConfig() 0 4 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
     * @throw KumbiaException
47
     * @param  string $database base de datos a conectar
48
     * @param  bool   $force    forzar nueva conexion PDO
49
     * @return PDO
50
     */
51
    public static function get($database = 'default', $force = \false)
52
    {
53
        // Verifica el singleton
54
        if ( ! $force && isset(self::$pool[$database])) {
55
            return self::$pool[$database];
56
        }
57
58
        if ($force) {
59
            return self::connect(self::getConfig($database));
60
        }
61
62
        return self::$pool[$database] = self::connect(self::getConfig($database));
63
    }
64
65
    /**
66
     * Conexión a la base de datos.
67
     *
68
     * @param  array               $config Config base de datos a conectar
69
     * @throws \RuntimeException
70
     * @return PDO
71
     */
72
    private static function connect($config)
73
    {
74
        try {
75
            return new PDO($config['dsn'], $config['username'], $config['password'], $config['params']);
76
        } catch (\PDOException $e) {
77
            //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
     * @throws \RuntimeException
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
102
        return self::$config[$database] + [
103
            'dns'      => \null,
104
            'username' => \null,
105
            'password' => \null,
106
            'params'   => [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]
107
        ];
108
    }
109
110
    /**
111
     * Permite agregar una base de datos sin leer del archivo de configuracion.
112
     *
113
     * @param array $value Valores de la configuración
114
     */
115
    public static function setConfig(array $value)
116
    {
117
        self::$config = [] + self::$config + $value;
118
    }
119
}
120