Completed
Push — 2.0 ( c11079...9c6898 )
by Vermeulen
02:10
created

Modeles::obtainSqlConnect()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 8.439
c 0
b 0
f 0
cc 6
eloc 15
nc 4
nop 0
1
<?php
2
3
namespace BfwSql;
4
5
use \Exception;
6
7
/**
8
 * Abstract class for all Models class
9
 * 
10
 * @package bfw-sql
11
 * @author Vermeulen Maxime <[email protected]>
12
 * @version 2.0
13
 */
14
abstract class Modeles extends \BfwSql\Sql
15
{
16
    /**
17
     * @var $tableName The table name
18
     */
19
    protected $tableName = '';
20
    
21
    /**
22
     * @var $tableNameWithPrefix the table name with prefix
23
     */
24
    protected $tableNameWithPrefix = '';
25
    
26
    /**
27
     * @var $baseKeyName The baseKeyName to use to connection.
28
     *  Use it if they are multiple database to connect in the application.
29
     */
30
    protected $baseKeyName = '';
31
    
32
    /**
33
     * Constructor
34
     */
35
    public function __construct()
36
    {
37
        $sqlConnect = $this->obtainSqlConnect();
38
        
39
        parent::__construct($sqlConnect);
40
        $this->tableNameWithPrefix = $this->prefix.$this->tableName;
41
    }
42
    
43
    /**
44
     * Get the BFW Application
45
     * It's a dedicated method for unit test or case where App is override
46
     * 
47
     * @return \BFW\Application
48
     */
49
    protected function getApp()
50
    {
51
        return \BFW\Application::getInstance();
52
    }
53
    
54
    /**
55
     * Obtain SqlConnect instance for the baseKeyName
56
     * 
57
     * @return \BfwSql\SqlConnect
58
     * 
59
     * @throws \Exception If there are many connection declared and if the
60
     *  property baseKeyName is empty
61
     */
62
    protected function obtainSqlConnect()
63
    {
64
        $listBases = $this->getApp()->getModule('bfw-sql')->listBases;
65
        
66
        if (count($listBases) > 1 && empty($this->baseKeyName)) {
67
            throw new Exception(
68
                'They are multiple connection, '
69
                .'so the property baseKeyName must be defined'
70
            );
71
        }
72
        
73
        if (count($listBases) > 1 && !isset($listBases[$this->baseKeyName])) {
74
            throw new Exception(
75
                'They are multiple connection, '
76
                .'but the connection '.$this->baseKeyName.' is not defined.'
77
            );
78
        }
79
        
80
        if (count($listBases) === 1) {
81
            $sqlConnect = current($listBases);
82
        } else {
83
            $sqlConnect = $listBases[$this->baseKeyName];
84
        }
85
        
86
        return $sqlConnect;
87
    }
88
}
89