Completed
Push — 2.0 ( fc981a...c11079 )
by Vermeulen
01:48
created

Sql::createId()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 33
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 33
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 18
nc 3
nop 2
1
<?php
2
3
namespace BfwSql;
4
5
use \Exception;
6
7
/**
8
 * Class to access to query writer
9
 * 
10
 * @package bfw-sql
11
 * @author Vermeulen Maxime <[email protected]>
12
 * @version 2.0
13
 */
14
class Sql
15
{
16
    /**
17
     * @var \BfwSql\SqlConnect $sqlConnect SqlConnect object
18
     */
19
    protected $sqlConnect;
20
    
21
    /**
22
     * @var string $prefix Tables prefix
23
     */
24
    protected $prefix = '';
25
    
26
    /**
27
     * Constructor
28
     * 
29
     * @param \BfwSql\SqlConnect $sqlConnect SqlConnect instance
30
     * 
31
     * @throws \Exception
32
     */
33
    public function __construct(\BfwSql\SqlConnect $sqlConnect)
34
    {
35
        $this->sqlConnect = $sqlConnect;
36
        $this->prefix     = $sqlConnect->getConnectionInfos()->tablePrefix;
37
    }
38
    
39
    /**
40
     * Getter to the property sqlConnect
41
     * 
42
     * @return \BFWSql\SqlConnect
43
     */
44
    public function getSqlConnect()
45
    {
46
        return $this->sqlConnect;
47
    }
48
    
49
    /**
50
     * Getter to the property prefix
51
     * 
52
     * @return string
53
     */
54
    public function getPrefix()
55
    {
56
        return $this->prefix;
57
    }
58
    
59
    /**
60
     * Get the id for the last item has been insert in database
61
     * 
62
     * @param string|null $name (default: null) Name of the sequence for the id
63
     *  Used for SGDB like PostgreSQL. Not use it for mysql.
64
     * 
65
     * @return integer
66
     */
67
    public function getLastInsertedId($name = null)
68
    {
69
        return (int) $this->sqlConnect->getPDO()->lastInsertId($name);
70
    }
71
    
72
    /**
73
     * Get the id for the last item has been insert in database for a table
74
     * without auto-increment
75
     * 
76
     * @param string       $table The table name
77
     * @param string       $colId The column name for the ID
78
     * @param string|array $order Columns to sort table content
79
     * @param string|array $where All where instruction used for filter content
80
     * 
81
     * @return integer
82
     */
83
    public function getLastInsertedIdWithoutAI(
84
        $table,
85
        $colId,
86
        $order,
87
        $where = ''
88
    ) {
89
        $req = $this->select()
90
                    ->from($table, $colId)
91
                    ->limit(1);
92
    
93
        if (is_array($where)) {
94
            foreach ($where as $val) {
95
                $req->where($val);
96
            }
97
        } elseif ($where != '') {
98
            $req->where($where);
99
        }
100
        
101
        if (is_array($order)) {
102
            foreach ($order as $val) {
103
                $req->order($val);
104
            }
105
        } else {
106
            $req->order($order);
107
        }
108
        
109
        $res = $req->fetchRow();
110
        $req->closeCursor();
111
        
112
        if ($res) {
113
            return (int) $res[$colId];
114
        }
115
        
116
        return 0;
117
    }
118
    
119
    /**
120
     * Return a new instance of SqlSelect
121
     * 
122
     * @param string $type (default: "array") Return PHP type
123
     *  Possible value : "array" or "object"
124
     * 
125
     * @return \BfwSql\SqlSelect
126
     */
127
    public function select($type = 'array')
128
    {
129
        return new SqlSelect($this->sqlConnect, $type);
130
    }
131
    
132
    /**
133
     * Return a new instance of SqlInsert
134
     * 
135
     * @param string $table   The table concerned by the request
136
     * @param array  $columns (default: null) All datas to add
137
     *  Format is array('columnName' => 'value', ...);
138
     * 
139
     * @return \BfwSql\SqlInsert
140
     */
141
    public function insert($table, $columns = null)
142
    {
143
        return new SqlInsert($this->sqlConnect, $table, $columns);
144
    }
145
    
146
    /**
147
     * Return a new instance of SqlUpdate
148
     * 
149
     * @param string $table   The table concerned by the request
150
     * @param array  $columns (default: null) All datas to update
151
     *  Format is array('columnName' => 'newValue', ...);
152
     * 
153
     * @return \BfwSql\SqlUpdate
154
     */
155
    public function update($table, $columns = null)
156
    {
157
        return new SqlUpdate($this->sqlConnect, $table, $columns);
158
    }
159
    
160
    /**
161
     * Return a new instance of SqlDelete
162
     * 
163
     * @param string $table The table concerned by the request
164
     * 
165
     * @return \BfwSql\SqlDelete
166
     */
167
    public function delete($table)
168
    {
169
        return new SqlDelete($this->sqlConnect, $table);
170
    }
171
    
172
    /**
173
     * Find the first vacant id on a table and for a column
174
     * 
175
     * @param string $table  The table concerned by the request
176
     * @param string $column The id column. Must be an integer..
177
     * 
178
     * @throws \Exception If a error has been throw during the search
179
     * 
180
     * @return integer
181
     */
182
    public function createId($table, $column)
183
    {
184
        //Search the first line in the table
185
        $reqFirstLine = $this->select()
186
            ->from($table, $column)
187
            ->order($column.' ASC')
188
            ->limit(1);
189
        
190
        $resFirstLine = $reqFirstLine->fetchRow();
191
        $reqFirstLine->closeCursor();
192
        
193
        // If nothing in the table. First AI is 1
194
        if (!$resFirstLine) {
195
            return 1;
196
        }
197
        
198
        // If the id for the first line is > 1
199
        if ($resFirstLine[$column] > 1) {
200
            return $resFirstLine[$column] - 1;
201
        }
202
        
203
        //First line have ID=1, we search from the end
204
        $reqLastLine = $this->select()
205
            ->from($table, $column)
206
            ->order($column.' DESC')
207
            ->limit(1);
208
        
209
        $resLastLine = $reqLastLine->fetchRow();
210
        $reqLastLine->closeCursor();
211
212
        //Get the last ID and add 1
213
        return $resLastLine[$column] + 1;
214
    }
215
    
216
    /**
217
     * Run the query in parameter 
218
     * 
219
     * @param string $request The request to run
220
     * 
221
     * @throws \Exception If the request has failed
222
     * 
223
     * @return \PDOStatement
224
     */
225
    public function query($request)
226
    {
227
        $this->sqlConnect->upNbQuery();
228
        
229
        $req   = $this->sqlConnect->getPDO()->query($request);
230
        $error = $this->sqlConnect->getPDO()->errorInfo();
231
        
232
        if (
233
            !$req
234
            && $error[0] !== null
235
            && $error[0] !== '00000'
236
            && isset($error[2])
237
        ) {
238
            throw new Exception($error[2]);
239
        }
240
        
241
        return $req;
242
    }
243
}
244