GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 37c075...91da2e )
by cao
03:14
created

WhereImpl::having()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 9
Ratio 100 %

Code Coverage

Tests 5
CRAP Score 2.0185

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 3
dl 9
loc 9
ccs 5
cts 6
cp 0.8333
crap 2.0185
rs 9.6666
c 0
b 0
f 0
1
<?php
2
3
namespace PhpBoot\DB\impls;
4
use PhpBoot\DB\DB;
5
use PhpBoot\DB\NestedStringCut;
6
use PhpBoot\DB\Raw;
7
use PhpBoot\DB\rules\basic\BasicRule;
8
use PhpBoot\DB\Context;
9
10
class ExecResult{
11 25
    public function __construct($success, $pdo, $st){
12 25
        $this->pdo = $pdo;
13 25
        $this->st = $st;
14 25
        $this->success = $success;
15 25
        $this->rows = $this->st->rowCount();
16 25
    }
17 1
    public function lastInsertId($name=null){
18 1
        return $this->pdo->lastInsertId($name);
19
    }
20
    /**
21
     * @var bool
22
     * true on success or false on failure.
23
     */
24
    public $success;
25
    /**
26
     * @var int
27
     * the number of rows.
28
     */
29
    public $rows;
30
    /**
31
     *
32
     * @var \PDO
33
     */
34
    public $pdo;
35
36
    /**
37
     * @var \PDOStatement
38
     */
39
    public $st;
40
}
41
42
class SelectImpl
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
43
{
44 24
    static  public function select($context, $columns){
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
45 24
        $context->appendSql("SELECT $columns");
46 24
    }
47
}
48
49
class FromImpl
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
50
{
51 23
    static public function from($context, $tables,$as=null){
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
52 23
        if($tables instanceof BasicRule){
53
            $context->appendSql("FROM (".$tables->context->sql.')');
54
            $context->params = array_merge($context->params,$tables->context->params);
55
        }else {
56 23
            $context->appendSql("FROM ".DB::wrap($tables));
57
        }
58 23
        if($as){
59
            $context->appendSql("as ".DB::wrap($as));
60
        }
61 23
    }
62
}
63
64
class DeleteImpl
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
65
{
66 7
    static public function deleteFrom($context, $from)
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
67
    {
68 7
        $context->appendSql("DELETE FROM ".DB::wrap($from));
69 7
    }
70
}
71
72
class JoinImpl
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
73
{
74 5
    static public function join($context, $type, $table) {
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
75 5
        $table = DB::wrap($table);
76 5
        if($type){
77 3
            $context->appendSql("$type JOIN $table");
78 3
        }else{
79 2
            $context->appendSql("JOIN $table");
80
        }
81 5
    }
82
}
83
84
class JoinOnImpl
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
85
{
86 5
    static public function on($context, $condition) {
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
87 5
        $context->appendSql("ON $condition");
88 5
    }
89
}
90
91
class ForUpdateImpl
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
92
{
93 2
    static public function forUpdate($context){
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
94 2
        $context->appendSql("FOR UPDATE");
95 2
    }
96
}
97
98
class ForUpdateOfImpl
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
99
{
100 1
    static public function of($context, $column){
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
101 1
        $column = DB::wrap($column);
102 1
        $context->appendSql("OF $column");
103 1
    }
104
}
105
106
class InsertImpl
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
107
{
108 5
    static public function insertInto($context, $table) {
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
109 5
        $table = DB::wrap($table);
110 5
        $context->appendSql("INSERT INTO $table");
111 5
    }
112
}
113
class ReplaceImpl
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
114
{
115 2
    static public function replaceInto($context, $table) {
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
116 2
        $table = DB::wrap($table);
117 2
        $context->appendSql("REPLACE INTO $table");
118 2
    }
119
}
120
class ValuesImpl
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
121
{
122 7
    static public function values($context, $values){
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
123 7
        $params = [];
124 7
        $stubs = [];
125 7
        foreach ($values as $v){
126 7
            if(is_a($v, Raw::class)){//直接拼接sql,不需要转义
127 4
                $stubs[]=$v->get();
128 4
            }else{
129 7
                $stubs[]='?';
130 7
                $params[] = $v;
131
            }
132 7
        }
133 7
        $stubs = implode(',', $stubs);
134
135 7
        if(array_keys($values) === range(0, count($values) - 1)){
136
            //VALUES(val0, val1, val2)
0 ignored issues
show
Unused Code Comprehensibility introduced by
40% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
137 4
            $context->appendSql("VALUES($stubs)");
138
139 4
        }else{
140
            //(col0, col1, col2) VALUES(val0, val1, val2)
0 ignored issues
show
Unused Code Comprehensibility introduced by
40% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
141
            $columns = implode(',', array_map(function($k){return DB::wrap($k);}, array_keys($values)));
142 3
            $context->appendSql("($columns) VALUES($stubs)",false);
143
        }
144 7
        $context->appendParams($params);
145 7
    }
146
    private $sql = null;
0 ignored issues
show
Unused Code introduced by
The property $sql is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
147
}
148
149
class UpdateImpl
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
150
{
151 11
    static public function update($context, $table){
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
152 11
        $table = DB::wrap($table);
153 11
        $context->appendSql("UPDATE $table");
154 11
    }
155
}
156
157
class UpdateSetImpl
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
158
{
159 11
    public function set(Context $context, $expr, $args){
160 11
        if(is_string($expr)){
161
            return $this->setExpr($context, $expr, $args);
162
        }else{
163 11
            return $this->setArgs($context, $expr);
164
        }
165
    }
166
167
    public function setExpr(Context $context, $expr, $args){
168
        if($this->first){
169
            $this->first = false;
170
            $prefix = 'SET ';
171
        }else{
172
            $prefix = ',';
173
        }
174
175
        $context->appendSql("$prefix$expr",$prefix == 'SET ');
176
        $context->appendParams($args);
177
178
    }
179 11 View Code Duplication
    public function setArgs(Context $context, $values){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
180 11
        $set = [];
181 11
        $params = [];
182 11
        foreach ($values as $k=>$v){
183 11
            $k = DB::wrap($k);
184 11
            if(is_a($v, Raw::class)){//直接拼接sql,不需要转义
185 1
                $set[]= "$k=".$v->get();
186 1
            }else{
187 11
                $set[]= "$k=?";
188 11
                $params[]=$v;
189
            }
190 11
        }
191 11
        if($this->first){
192 11
            $this->first = false;
193 11
            $context->appendSql('SET '.implode(',', $set));
194 11
            $context->appendParams($params);
195 11
        }else{
196
            $context->appendSql(','.implode(',', $set),false);
197
            $context->appendParams($params);
198
        }
199 11
    }
200
    private $first=true;
201
}
202
class OrderByImpl
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
203
{
204 7
    public function orderByArgs(Context $context, $orders){
205 7
        if(empty($orders)){
206
            return $this;
207
        }
208 7
        $params = array();
209 7
        foreach ($orders as $k=>$v){
210 7
            if(is_integer($k)){
211 6
                $params[] = DB::wrap($v);
212 6
            }else{
213 2
                $k = DB::wrap($k);
214
215 2
                $v = strtoupper($v);
216 2
                ($v =='DESC' || $v =='ASC') or \PhpBoot\abort( new \InvalidArgumentException("invalid params for orderBy(".json_encode($orders).")"));
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
217
218 2
                $params[] = "$k $v";
219
            }
220 7
        }
221 7
        if($this->first){
222 7
            $this->first = false;
223 7
            $context->appendSql('ORDER BY '.implode(',', $params));
224 7
        }else{
225 1
            $context->appendSql(','.implode(',', $params),false);
226
        }
227 7
        return $this;
228
    }
229 7
    public function orderBy(Context $context, $column, $order=null){
230 7
        if(is_string($column)){
231 7
            if($order === null){
232 6
                $column = [$column];
233 6
            }else{
234 2
                $column = [$column=>$order];
235
            }
236 7
        }
237 7
        return $this->orderByArgs($context, $column);
238
239
240
    }
241
    private $first=true;
242
}
243
244
class LimitImpl
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
245
{
246 3
    static public function limit(Context $context, $size){
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
247 3
        $intSize = intval($size);
248 3
        strval($intSize) == $size or \PhpBoot\abort(
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
249
            new \InvalidArgumentException("invalid params for limit($size)"));
250 3
        $context->appendSql("LIMIT $size");
251 3
    }
252 1
    static public function limitWithOffset(Context $context, $start, $size){
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
253 1
        $intStart = intval($start);
254 1
        $intSize = intval($size);
255 1
        strval($intStart) == $start && strval($intSize) == $size or \PhpBoot\abort(
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
256
            new \InvalidArgumentException("invalid params for limit($start, $size)"));
257 1
        $context->appendSql("LIMIT $start,$size");
258 1
    }
259
}
260
261
class WhereImpl{
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
262
263 1
    static private function findQ($str,$offset = 0,$no=0){
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
264 1
        $found = strpos($str, '?', $offset);
265 1
        if($no == 0 || $found === false){
266 1
            return $found;
267
        }
268 1
        return self::findQ($str, $found+1, $no-1);
269
    }
270
271 27
    static public function where(Context $context, $prefix, $expr, $args){
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
272 27
        if(empty($expr)){
273 1
            return;
274
        }
275 26
        if(is_callable($expr)){
276 3
            self::conditionClosure($context,$prefix, $expr);
277 26
        }elseif (is_string($expr)){
278 14
            self::condition($context, $prefix, $expr, $args);
279 14
        }else{
280 13
            self::conditionArgs($context, $prefix, $expr);
281
        }
282
283 26
    }
284
285 3
    static public function conditionClosure(Context $context, $prefix, callable $callback){
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
286 3
        $context->appendSql($prefix.' (');
287 3
        $callback($context);
288 3
        $context->appendSql(')');
289 3
    }
290
    /**
291
     * find like Mongodb query glossary
292
     * whereArray(
293
     *      [
294
     *          'id'=>['>'=>1],
295
     *          'name'=>'cym',
296
     *      ]
297
     * )
298
     * 支持的操作符有
299
     * =    'id'=>['=' => 1]
300
     * >    'id'=>['>' => 1]
301
     * <    'id'=>['<' => 1]
302
     * <>   'id'=>['<>' => 1]
303
     * >=   'id'=>['>=' => 1]
304
     * <=   'id'=>['<=' => 1]
305
     * BETWEEN  'id'=>['BETWEEN' => [1 ,2]]
306
     * LIKE     'id'=>['LIKE' => '1%']
307
     * IN   'id'=>['IN' => [1,2,3]]
308
     * NOT IN   'id'=>['NOT IN' => [1,2,3]]
309
     * @return void
310
     */
311 13
    static public function conditionArgs(Context $context, $prefix, $args=[]){
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
312 13
        if($args ===null){
313
            return ;
314
        }
315 13
        $exprs = array();
316 13
        $params = array();
317 13
        foreach ($args as $k => $v){
318 13
            $k = DB::wrap($k);
319 13
            if(is_array($v)){
320 1
                $ops = ['=', '>', '<', '<>', '>=', '<=', 'IN', 'NOT IN', 'BETWEEN', 'LIKE'];
321 1
                $op = array_keys($v)[0];
322 1
                $op = strtoupper($op);
323
324 1
                false !== array_search($op, $ops) or \PhpBoot\abort(
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
325
                    new \InvalidArgumentException("invalid param $op for whereArgs"));
326
327 1
                $var = array_values($v)[0];
328 1
                if($op == 'IN' || $op == 'NOT IN'){
329 1
                    $stubs = [];
330 1 View Code Duplication
                    foreach ($var as $i){
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
331 1
                        if(is_a($i, Raw::class)){
332 1
                            $stubs[]=strval($i);
333 1
                        }else{
334 1
                            $stubs[]='?';
335 1
                            $params[] = $i;
336
                        }
337 1
                    }
338 1
                    $stubs = implode(',', $stubs);
339 1
                    $exprs[] = "$k $op ($stubs)";
340 1
                }else if($op == 'BETWEEN'){
341 1
                    $cond = "$k BETWEEN";
342 1 View Code Duplication
                    if(is_a($var[0], Raw::class)){
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
343
                        $cond = "$cond ".strval($var[0]);
344
                    }else{
345 1
                        $cond = "$cond ?";
346 1
                        $params[] = $var[0];
347
                    }
348 1 View Code Duplication
                    if(is_a($var[1], Raw::class)){
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
349 1
                        $cond = "$cond AND ".strval($var[1]);
350 1
                    }else{
351
                        $cond = "$cond AND ?";
352
                        $params[] = $var[1];
353
                    }
354 1
                    $exprs[] = $cond;
355 1
                }else{
356 1
                    if(is_a($var, Raw::class)){
357
                        $exprs[] = "$k $op ".strval($var);
358
                    }else{
359 1
                        $exprs[] = "$k $op ?";
360 1
                        $params[] = $var;
361
                    }
362
                }
363 1
            }else{
364 13
                if(is_a($v, Raw::class)){
365 1
                    $exprs[] = "$k = ".strval($v);
366
367 1
                }else{
368 13
                    $exprs[] = "$k = ?";
369 13
                    $params[] = $v;
370
                }
371
            }
372 13
        }
373
374 13
        self::condition($context, $prefix, implode(' AND ', $exprs), $params);
375 13
    }
376 26
    static public function condition(Context $context, $prefix, $expr, $args){
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
377 26
        if(!empty($expr)){
378 26
            $expr = "($expr)";
379 26
            if($args){
380
                //因为PDO不支持绑定数组变量, 这里需要手动展开数组
381
                //也就是说把 where("id IN(?)", [1,2])  展开成 where("id IN(?,?)", 1,2)
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
382 25
                $cutted = null;
383 25
                $cut = null;
384 25
                $toReplace = array();
385
386 25
                $newArgs=array();
387
                //找到所有数组对应的?符位置
388 25
                foreach ($args as $k =>$arg){
389 25
                    if(is_array($arg) || is_a($arg, Raw::class)){
390 1
                        if(!$cutted){
0 ignored issues
show
Bug Best Practice introduced by
The expression $cutted of type null|string is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
391 1
                            $cut = new NestedStringCut($expr);
392 1
                            $cutted = $cut->getText();
393 1
                        }
394
                        //找到第$k个?符
395 1
                        $pos = self::findQ($cutted, 0, $k);
396 1
                        $pos = $cut->mapPos($pos);
397 1
                        $pos !== false or \PhpBoot\abort(
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
398
                            new \InvalidArgumentException("unmatched params and ? @ $expr"));
399
400 1
                        if(is_array($arg)){
401 1
                            $stubs = [];
402 1 View Code Duplication
                            foreach ($arg as $i){
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
403 1
                                if(is_a($i, Raw::class)){
404 1
                                    $stubs[] = strval($i);
405 1
                                }else{
406 1
                                    $stubs[] = '?';
407 1
                                    $newArgs[] = $i;
408
                                }
409 1
                            }
410 1
                            $stubs = implode(',', $stubs);
411 1
                        }else{
412 1
                            $stubs = strval($arg);
413
                        }
414 1
                        $toReplace[] = [$pos, $stubs];
415
416 1
                    }else{
417 25
                        $newArgs[]=$arg;
418
                    }
419 25
                }
420
421 25
                if(count($toReplace)){
422 1
                    $toReplace = array_reverse($toReplace);
423 1
                    foreach ($toReplace as $i){
424 1
                        list($pos, $v) = $i;
425 1
                        $expr = substr($expr, 0, $pos).$v. substr($expr, $pos+1);
426 1
                    }
427 1
                    $args = $newArgs;
428 1
                }
429 25
            }
430 26
            if($prefix){
431 26
                $context->appendSql($prefix.' '.$expr);
432 26
            }else{
433 3
                $context->appendSql($expr);
434
            }
435
436 26
            if($args){
437 25
                $context->appendParams($args);
438 25
            }
439 26
        }
440 26
    }
441
}
442
443
class GroupByImpl{
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
444 5
    static public function groupBy(Context $context, $column){
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
445 5
        $column = DB::wrap($column);
446 5
        $context->appendSql("GROUP BY $column");
447 5
    }
448
}
449
450
class ExecImpl
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
451
{
452
    /**
453
     *
454
     * @param Context $context
455
     * @param $exceOnError boolean whether throw exceptions
456
     * @return ExecResult
457
     */
458 25
    static public function exec($context) {
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
459 25
        $st = $context->connection->prepare($context->sql);
460 25
        $success = $st->execute($context->params);
461 25
        return new ExecResult($success, $context->connection, $st);
462
    }
463
    /**
464
     *
465
     * @param Context $context
466
     * @param string|false $asDict return  as dict or array
0 ignored issues
show
Bug introduced by
There is no parameter named $asDict. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
467
     * @return false|array
468
     */
469 24
    static public function get($context, $dictAs=false){
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
470
471 24
        $st = $context->connection->prepare($context->sql);
472 24
        if($st->execute($context->params)){
473
            $res = $st->fetchAll(\PDO::FETCH_ASSOC);
474
            if ($dictAs){
475
                $dict= [];
476
                foreach ($res as $i){
477
                    $dict[$i[$dictAs]]=$i;
478
                }
479
                return $context->handleResult($dict);
480
            }
481
            return $context->handleResult($res);
482
        }else{
483 24
            return false;
484
        }
485
    }
486
487
    /**
488
     * @param Context $context
489
     * @return int|false
490
     */
491
    static public function count($context){
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
492
493
        $found = [];
494
        if(!preg_match('/\bselect\b/i', $context->sql, $found, PREG_OFFSET_CAPTURE) ||
495
            count($found)==0){
496
            \PhpBoot\abort(new \PDOException("can not use count(*) without select"));
497
        }
498
        list($chars, $columnBegin) = $found[0];
0 ignored issues
show
Unused Code introduced by
The assignment to $chars is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
499
        $columnBegin = $columnBegin + strlen('select')+1;
500
501
        $columnEnd = 0;
502
        $found = [];
503
        if(!preg_match('/\bfrom\b/i', $context->sql, $found, PREG_OFFSET_CAPTURE) ||
504
            count($found)==0){
505
            $columnEnd = strlen($context->sql);
506
        }else{
507
            list($chars, $columnEnd) = $found[0];
0 ignored issues
show
Unused Code introduced by
The assignment to $chars is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
508
        }
509
        $sql = substr($context->sql, 0, $columnBegin);
510
        $sql .= ' COUNT(*) as `count` ';
511
        $sql .= substr($context->sql, $columnEnd);
512
513
        $st = $context->connection->prepare($sql);
514
        if($st->execute($context->params)){
515
            $res = $st->fetchAll(\PDO::FETCH_ASSOC);
516
            return $res[0]['count'];
517
        }else{
518
            return false;
519
        }
520
521
    }
522
}
523
class OnDuplicateKeyUpdateImpl
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
524
{
525 1
    public function set($context, $column, $value){
526 1
        if(is_string($column)){
527 1
            $this->setExpr($context, $column, $value);
528 1
        }else{
529 1
            $this->setArgs($context, $column);
530
        }
531 1
    }
532
533 1
    public function setExpr($context, $expr, $args){
534 1
        $prefix = '';
0 ignored issues
show
Unused Code introduced by
$prefix is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
535 1
        if($this->first){
536 1
            $this->first = false;
537 1
            $prefix = 'ON DUPLICATE KEY UPDATE ';
538 1
        }else{
539
            $prefix = ',';
540
        }
541
542 1
        $context->appendSql("$prefix$expr",$prefix == 'ON DUPLICATE KEY UPDATE ');
543 1
        $context->appendParams($args);
544
545 1
    }
546 1 View Code Duplication
    public function setArgs($context, $values){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
547 1
        $set = [];
548 1
        $params = [];
549 1
        foreach ($values as $k=>$v){
550 1
            $k = DB::wrap($k);
551 1
            if(is_a($v, Raw::class)){//直接拼接sql,不需要转义
552 1
                $set[]= "$k=".$v->get();
553 1
            }else{
554
                $set[]= "$k=?";
555
                $params[]=$v;
556
            }
557 1
        }
558 1
        if($this->first){
559 1
            $this->first = false;
560 1
            $context->appendSql('ON DUPLICATE KEY UPDATE '.implode(',', $set));
561 1
            $context->appendParams($params);
562 1
        }else{
563
            $context->appendSql(','.implode(',', $set),false);
564
            $context->appendParams($params);
565
        }
566 1
    }
567
    private $first=true;
568
}
569