Passed
Push — master ( c76517...75329d )
by Runner
02:47
created

Database::has()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

Changes 0
Metric Value
cc 3
eloc 6
c 0
b 0
f 0
nc 2
nop 3
dl 0
loc 12
ccs 5
cts 6
cp 0.8333
crap 3.0416
rs 9.4285
1
<?php
2
/**
3
 * @author    jan huang <[email protected]>
4
 * @copyright 2016
5
 *
6
 * @see      https://www.github.com/janhuang
7
 * @see      http://www.fast-d.cn/
8
 */
9
10
namespace FastD\Model;
11
12
use Exception;
13
use Medoo\Medoo;
14
use PDO;
15
16
/**
17
 * Class Database.
18
 */
19
class Database extends Medoo
20
{
21
    /**
22
     * @var array|null
23
     */
24
    protected $config = [];
25
26
    /**
27
     * @var PDO
28
     */
29
    public $pdo;
30
31
    /**
32
     * Database constructor.
33
     *
34
     * @param array $options
35
     */
36 44
    public function __construct(array $options = null)
37
    {
38 44
        $this->config = $options;
39
40 44
        parent::__construct($this->config);
41
42 44
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
43 44
        $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
44 44
        $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
45 44
        $this->pdo->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false);
46 44
    }
47
48
    /**
49
     * reconnect database.
50
     */
51
    public function reconnect()
52
    {
53
        $this->__construct($this->config);
54
    }
55
56
    /**
57
     * @param $query
58
     *
59
     * @return bool|\PDOStatement
60
     */
61 3
    public function query($query)
62
    {
63
        try {
64 3
            return parent::query($query);
65
        } catch (Exception $e) {
66
            $this->reconnect();
67
68
            return parent::query($query);
69
        }
70
    }
71
72
    /**
73
     * @param $query
74
     *
75
     * @return bool|\PDOStatement
76
     */
77 1
    public function exec($query)
78
    {
79
        try {
80 1
            return parent::exec($query);
81
        } catch (Exception $e) {
82
            $this->reconnect();
83
84
            return parent::exec($query);
85
        }
86
    }
87
88 1
    public function has($table, $join, $where = null)
89
    {
90 1
        $column = null;
91
92 1
        $query = $this->query('SELECT EXISTS('.$this->selectContext($table, $join, $column, $where, 1).')');
93
94 1
        if ($query && intval($query->fetchColumn()) === 1) {
95 1
            return true;
96
        }
97
98
        return false;
99
    }
100
}
101