Passed
Branch wip_sessions (2e0cc8)
by Nils
04:43
created

Database   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 25
dl 0
loc 48
rs 10
c 0
b 0
f 0
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 3
A select() 0 10 2
A executeStatement() 0 18 4
1
<?php
2
/**
3
 * Teampass - a collaborative passwords manager.
4
 * ---
5
 * This library is distributed in the hope that it will be useful,
6
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
7
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
8
 * ---
9
 *
10
 * @project   Teampass
11
 * @version    API
12
 *
13
 * @file      Database.php
14
 * ---
15
 *
16
 * @author    Nils Laumaillé ([email protected])
17
 *
18
 * @copyright 2009-2023 Teampass.net
19
 *
20
 * @license   https://spdx.org/licenses/GPL-3.0-only.html#licenseText GPL-3.0
21
 * ---
22
 *
23
 * @see       https://www.teampass.net
24
 */
25
class Database
26
{
27
    protected $connection = null;
28
29
    public function __construct()
30
    {
31
        try {
32
            $this->connection = new \mysqli(DB_HOST, DB_USER, DB_PASSWD_CLEAR, DB_NAME);
33
34
            if ( mysqli_connect_errno()) {
35
                throw new Exception("Could not connect to database.");   
36
            }
37
        } catch (Exception $e) {
38
            throw new Exception($e->getMessage());   
39
        }           
40
    }
41
42
    public function select($query = "" , $params = [])
43
    {
44
        try {
45
            $stmt = $this->executeStatement( $query , $params );
46
            $result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);               
47
            $stmt->close();
48
49
            return $result;
50
        } catch(Exception $e) {
51
            throw New Exception( $e->getMessage() );
52
        }
53
    }
54
55
    private function executeStatement($query = "" , $params = [])
56
    {
57
        try {
58
            $stmt = $this->connection->prepare( $query );
59
60
            if($stmt === false) {
61
                throw New Exception("Unable to do prepared statement: " . $query);
62
            }
63
64
            if( $params ) {
65
                $stmt->bind_param($params[0], $params[1]);
66
            }
67
68
            $stmt->execute();
69
70
            return $stmt;
71
        } catch(Exception $e) {
72
            throw New Exception( $e->getMessage() );
73
        }   
74
    }
75
}