Completed
Push — 6.0 ( a1442b...a10566 )
by liu
04:56 queued 10s
created

Db::instance()   A

Complexity

Conditions 6
Paths 8

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
eloc 9
nc 8
nop 2
dl 0
loc 18
ccs 0
cts 10
cp 0
crap 42
rs 9.2222
c 0
b 0
f 0
1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
6
// +----------------------------------------------------------------------
7
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
8
// +----------------------------------------------------------------------
9
// | Author: liu21st <[email protected]>
10
// +----------------------------------------------------------------------
11
declare (strict_types = 1);
12
13
namespace think;
14
15
use InvalidArgumentException;
16
use think\db\BaseQuery;
17
use think\db\Connection;
18
use think\db\Raw;
19
20
/**
21
 * Class Db
22
 * @package think
0 ignored issues
show
Coding Style introduced by
Package name "think" is not valid; consider "Think" instead
Loading history...
23
 * @mixin BaseQuery
24
 * @mixin Query
25
 */
26
class Db
27
{
28
    /**
29
     * 数据库连接实例
30
     * @var array
31
     */
32
    protected $instance = [];
33
34
    /**
35
     * Event对象
36
     * @var Event
37
     */
38
    protected $event;
39
40
    /**
41
     * 数据库配置
42
     * @var array
43
     */
44
    protected $config = [];
45
46
    /**
47
     * SQL监听
48
     * @var array
49
     */
50
    protected $listen = [];
51
52
    /**
53
     * 查询次数
54
     * @var int
55
     */
56
    protected $queryTimes = 0;
57
58
    /**
59
     * 架构函数
60
     * @param array $config 连接配置
61
     * @access public
62
     */
63 1
    public function __construct(array $config = [])
64
    {
65 1
        $this->config = $config;
66
67 1
    }
68
69
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
70
     * @param Event  $event
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
71
     * @param Config $config
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
72
     * @return Db
73
     * @codeCoverageIgnore
74
     */
75
    public static function __make(Event $event, Config $config)
2 ignored issues
show
Coding Style introduced by
Method name "Db::__make" is invalid; only PHP magic methods should be prefixed with a double underscore
Loading history...
Coding Style introduced by
Public method name "Db::__make" must not be prefixed with an underscore
Loading history...
76
    {
77
        $db = new static($config->get('database'));
0 ignored issues
show
Bug introduced by
It seems like $config->get('database') can also be of type null; however, parameter $config of think\Db::__construct() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

77
        $db = new static(/** @scrutinizer ignore-type */ $config->get('database'));
Loading history...
78
79
        $db->setEvent($event);
80
81
        return $db;
82
    }
83
84
    /**
85
     * 创建/切换数据库连接查询
86
     * @access public
87
     * @param string|null $name 连接配置标识
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
88
     * @param bool        $force 强制重新连接
89
     * @return BaseQuery
90
     */
91
    public function connect(string $name = null, bool $force = false): BaseQuery
92
    {
93
        $connection = $this->instance($name, $force);
94
        $connection->setDb($this);
95
96
        $class = $connection->getQueryClass();
97
        $query = new $class($connection);
98
99
        if (!empty($this->config['time_query_rule'])) {
100
            $query->timeRule($this->config['time_query_rule']);
101
        }
102
103
        return $query;
104
    }
105
106
    /**
107
     * 创建数据库连接实例
108
     * @access protected
109
     * @param string|null $name  连接标识
110
     * @param bool        $force 强制重新连接
111
     * @return Connection
112
     */
113
    protected function instance(string $name = null, bool $force = false): Connection
114
    {
115
        if (empty($name)) {
116
            $name = $this->config['default'] ?? 'mysql';
117
        }
118
119
        if ($force || !isset($this->instance[$name])) {
120
            if (!isset($this->config['connections'][$name])) {
121
                throw new InvalidArgumentException('Undefined db config:' . $name);
122
            }
123
124
            $config = $this->config['connections'][$name];
125
            $type   = !empty($config['type']) ? $config['type'] : 'mysql';
126
127
            $this->instance[$name] = App::factory($type, '\\think\\db\\connector\\', $config);
128
        }
129
130
        return $this->instance[$name];
131
    }
132
133
    /**
134
     * 使用表达式设置数据
135
     * @access public
136
     * @param string $value 表达式
137
     * @return Raw
138
     */
139
    public function raw(string $value): Raw
140
    {
141
        return new Raw($value);
142
    }
143
144
    /**
145
     * 更新查询次数
146
     * @access public
147
     * @return void
148
     */
149
    public function updateQueryTimes(): void
150
    {
151
        $this->queryTimes++;
152
    }
153
154
    /**
155
     * 重置查询次数
156
     * @access public
157
     * @return void
158
     */
159
    public function clearQueryTimes(): void
160
    {
161
        $this->queryTimes = 0;
162
    }
163
164
    /**
165
     * 获得查询次数
166
     * @access public
167
     * @return integer
168
     */
169
    public function getQueryTimes(): int
170
    {
171
        return $this->queryTimes;
172
    }
173
174
    /**
175
     * 监听SQL执行
176
     * @access public
177
     * @param callable $callback 回调方法
178
     * @return void
179
     */
180
    public function listen(callable $callback): void
181
    {
182
        $this->listen[] = $callback;
183
    }
184
185
    /**
186
     * 获取监听SQL执行
187
     * @access public
188
     * @return array
189
     */
190
    public function getListen(): array
191
    {
192
        return $this->listen;
193
    }
194
195
    /**
196
     * 设置Event对象
197
     * @param Event $event
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
198
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
199
    public function setEvent(Event $event)
200
    {
201
        $this->event = $event;
202
    }
203
204
    /**
205
     * 注册回调方法
206
     * @access public
207
     * @param string   $event    事件名
208
     * @param callable $callback 回调方法
209
     * @return void
210
     */
211
    public function event(string $event, callable $callback): void
212
    {
213
        if ($this->event) {
214
            $this->event->listen('db.' . $event, $callback);
215
        }
216
    }
217
218
    /**
219
     * 触发事件
220
     * @access public
221
     * @param string $event  事件名
222
     * @param mixed  $params 传入参数
223
     * @param bool   $once
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
224
     * @return mixed
225
     */
226
    public function trigger(string $event, $params = null, bool $once = false)
227
    {
228
        if ($this->event) {
229
            return $this->event->trigger('db.' . $event, $params, $once);
230
        }
231
    }
232
233
    public function __call($method, $args)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __call()
Loading history...
234
    {
235
        return call_user_func_array([$this->connect(), $method], $args);
236
    }
237
}
238