Passed
Push — 5.1 ( d12c7f...922161 )
by liu
07:33
created

Mysql::parseKey()   D

Complexity

Conditions 20
Paths 55

Size

Total Lines 53
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 20
eloc 28
c 1
b 0
f 0
nc 55
nop 3
dl 0
loc 53
rs 4.1666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2018 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
12
namespace think\db\builder;
13
14
use think\db\Builder;
15
use think\db\Expression;
16
use think\db\Query;
17
use think\Exception;
18
19
/**
20
 * mysql数据库驱动
0 ignored issues
show
Coding Style introduced by
Doc comment short description must start with a capital letter
Loading history...
21
 */
22
class Mysql extends Builder
23
{
24
    // 查询表达式解析
25
    protected $parser = [
26
        'parseCompare'     => ['=', '<>', '>', '>=', '<', '<='],
27
        'parseLike'        => ['LIKE', 'NOT LIKE'],
28
        'parseBetween'     => ['NOT BETWEEN', 'BETWEEN'],
29
        'parseIn'          => ['NOT IN', 'IN'],
30
        'parseExp'         => ['EXP'],
31
        'parseRegexp'      => ['REGEXP', 'NOT REGEXP'],
32
        'parseNull'        => ['NOT NULL', 'NULL'],
33
        'parseBetweenTime' => ['BETWEEN TIME', 'NOT BETWEEN TIME'],
34
        'parseTime'        => ['< TIME', '> TIME', '<= TIME', '>= TIME'],
35
        'parseExists'      => ['NOT EXISTS', 'EXISTS'],
36
        'parseColumn'      => ['COLUMN'],
37
    ];
38
39
    protected $insertAllSql = '%INSERT% INTO %TABLE% (%FIELD%) VALUES %DATA% %COMMENT%';
40
    protected $updateSql    = 'UPDATE %TABLE% %JOIN% SET %SET% %WHERE% %ORDER%%LIMIT% %LOCK%%COMMENT%';
41
42
    /**
43
     * 生成insertall SQL
44
     * @access public
45
     * @param  Query     $query   查询对象
46
     * @param  array     $dataSet 数据集
47
     * @param  bool      $replace 是否replace
48
     * @return string
49
     */
50
    public function insertAll(Query $query, $dataSet, $replace = false)
51
    {
52
        $options = $query->getOptions();
53
54
        // 获取合法的字段
55
        if ('*' == $options['field']) {
56
            $allowFields = $this->connection->getTableFields($options['table']);
57
        } else {
58
            $allowFields = $options['field'];
59
        }
60
61
        // 获取绑定信息
62
        $bind = $this->connection->getFieldsBind($options['table']);
63
64
        foreach ($dataSet as $k => $data) {
65
            $data = $this->parseData($query, $data, $allowFields, $bind);
66
67
            $values[] = '( ' . implode(',', array_values($data)) . ' )';
68
69
            if (!isset($insertFields)) {
70
                $insertFields = array_keys($data);
71
            }
72
        }
73
74
        $fields = [];
75
        foreach ($insertFields as $field) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $insertFields seems to be defined by a foreach iteration on line 64. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
76
            $fields[] = $this->parseKey($query, $field);
77
        }
78
79
        return str_replace(
80
            ['%INSERT%', '%TABLE%', '%FIELD%', '%DATA%', '%COMMENT%'],
81
            [
82
                $replace ? 'REPLACE' : 'INSERT',
83
                $this->parseTable($query, $options['table']),
84
                implode(' , ', $fields),
85
                implode(' , ', $values),
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $values seems to be defined by a foreach iteration on line 64. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
86
                $this->parseComment($query, $options['comment']),
87
            ],
88
            $this->insertAllSql);
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 8 spaces, but found 12.
Loading history...
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
89
    }
90
91
    /**
92
     * 正则查询
93
     * @access protected
94
     * @param  Query        $query        查询对象
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 8 found
Loading history...
95
     * @param  string       $key
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
96
     * @param  string       $exp
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
97
     * @param  mixed        $value
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
98
     * @param  string       $field
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
99
     * @return string
100
     */
101
    protected function parseRegexp(Query $query, $key, $exp, $value, $field)
0 ignored issues
show
Unused Code introduced by
The parameter $query is not used and could be removed. ( Ignorable by Annotation )

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

101
    protected function parseRegexp(/** @scrutinizer ignore-unused */ Query $query, $key, $exp, $value, $field)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $field is not used and could be removed. ( Ignorable by Annotation )

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

101
    protected function parseRegexp(Query $query, $key, $exp, $value, /** @scrutinizer ignore-unused */ $field)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
102
    {
103
        if ($value instanceof Expression) {
104
            $value = $value->getValue();
105
        }
106
107
        return $key . ' ' . $exp . ' ' . $value;
108
    }
109
110
    /**
111
     * 字段和表名处理
112
     * @access public
113
     * @param  Query     $query 查询对象
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
114
     * @param  mixed     $key   字段名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 3 found
Loading history...
115
     * @param  bool      $strict   严格检测
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
116
     * @return string
117
     */
118
    public function parseKey(Query $query, $key, $strict = false)
119
    {
120
        if (is_numeric($key)) {
121
            return $key;
122
        } elseif ($key instanceof Expression) {
123
            return $key->getValue();
124
        }
125
126
        $key = trim($key);
127
128
        if(strpos($key, '->>') && false === strpos($key, '(')){
0 ignored issues
show
Coding Style introduced by
Expected "if (...) {\n"; found "if(...){\n"
Loading history...
Coding Style introduced by
There must be a single space between the closing parenthesis and the opening brace of a multi-line IF statement; found 0 spaces
Loading history...
129
            // JSON字段支持
130
            list($field, $name) = explode('->>', $key, 2);
131
132
            return $this->parseKey($query, $field, true) . '->>\'$' . (strpos($name, '[') === 0 ? '' : '.') . str_replace('->>', '.', $name) . '\'';
133
        }
134
        elseif (strpos($key, '->') && false === strpos($key, '(')) {
0 ignored issues
show
Coding Style introduced by
Expected "} elseif (...) \n"; found "\n elseif (...) {\n"
Loading history...
135
            // JSON字段支持
136
            list($field, $name) = explode('->', $key, 2);
137
138
            return 'json_extract(' . $this->parseKey($query, $field, true) . ', \'$' . (strpos($name, '[') === 0 ? '' : '.') . str_replace('->', '.', $name) . '\')';
139
        } elseif (strpos($key, '.') && !preg_match('/[,\'\"\(\)`\s]/', $key)) {
140
            list($table, $key) = explode('.', $key, 2);
141
142
            $alias = $query->getOptions('alias');
143
144
            if ('__TABLE__' == $table) {
145
                $table = $query->getOptions('table');
146
                $table = is_array($table) ? array_shift($table) : $table;
147
            }
148
149
            if (isset($alias[$table])) {
150
                $table = $alias[$table];
151
            }
152
        }
153
154
        if ($strict && !preg_match('/^[\w\.\*]+$/', $key)) {
155
            throw new Exception('not support data:' . $key);
156
        }
157
158
        if ('*' != $key && !preg_match('/[,\'\"\*\(\)`.\s]/', $key)) {
159
            $key = '`' . $key . '`';
160
        }
161
162
        if (isset($table)) {
163
            if (strpos($table, '.')) {
164
                $table = str_replace('.', '`.`', $table);
165
            }
166
167
            $key = '`' . $table . '`.' . $key;
168
        }
169
170
        return $key;
171
    }
172
173
    /**
174
     * 随机排序
175
     * @access protected
176
     * @param  Query     $query        查询对象
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 8 found
Loading history...
177
     * @return string
178
     */
179
    protected function parseRand(Query $query)
0 ignored issues
show
Unused Code introduced by
The parameter $query is not used and could be removed. ( Ignorable by Annotation )

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

179
    protected function parseRand(/** @scrutinizer ignore-unused */ Query $query)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
180
    {
181
        return 'rand()';
182
    }
183
184
}
185