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 ( 052e71...ab98e5 )
by cao
04:29
created

WhereImpl::findQ()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 2
nop 3
dl 0
loc 7
ccs 5
cts 5
cp 1
crap 3
rs 9.4285
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 28
    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 28
        $context->appendSql("SELECT $columns");
46 28
    }
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 27
    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 27
        if($tables instanceof BasicRule){
53 1
            $context->appendSql("FROM (".$tables->context->sql.')');
54 1
            $context->params = array_merge($context->params,$tables->context->params);
55 1
        }else {
56 27
            $context->appendSql("FROM ".DB::wrap($tables));
57
        }
58 27
        if($as){
59
            $context->appendSql("as ".DB::wrap($as));
60
        }
61 27
    }
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 2
    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 2
        $found = strpos($str, '?', $offset);
265 2
        if($no == 0 || $found === false){
266 2
            return $found;
267
        }
268 1
        return self::findQ($str, $found+1, $no-1);
269
    }
270
271 31
    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 31
        if(empty($expr)){
273 1
            return;
274
        }
275 30
        if(is_callable($expr)){
276 3
            self::conditionClosure($context,$prefix, $expr);
277 30
        }elseif (is_string($expr)){
278 15
            self::condition($context, $prefix, $expr, $args);
279 15
        }else{
280 17
            self::conditionArgs($context, $prefix, $expr);
281
        }
282
283 30
    }
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 17
    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 17
        if($args ===null){
313
            return ;
314
        }
315 17
        $exprs = array();
316 17
        $params = array();
317 17
        foreach ($args as $k => $v){
318 17
            $k = DB::wrap($k);
319 17
            if(!is_array($v)){
320 17
                $v = ['='=>$v];
321 17
            }
322
323 17
            $ops = ['=', '>', '<', '<>', '>=', '<=', 'IN', 'NOT IN', 'BETWEEN', 'LIKE'];
324 17
            $op = array_keys($v)[0];
325 17
            $op = strtoupper($op);
326
327 17
            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...
328
                new \InvalidArgumentException("invalid param $op for whereArgs"));
329
330 17
            $var = array_values($v)[0];
331 17
            if($op == 'IN' || $op == 'NOT IN'){
332 2
                $stubs = [];
333
334 2
                if($var instanceof BasicRule){
335 1
                    $stubs = "({$var->context->sql})";
336 1
                    $params = array_merge($params, $var->context->params);
337 1
                    $exprs[] = "$k $op $stubs";
338 1
                }else{
339 1
                    foreach ($var as $i){
340 1
                        if(is_a($i, Raw::class)){
341 1
                            $stubs[]=strval($i);
342 1 View Code Duplication
                        }elseif($i instanceof BasicRule){
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
                            $stubs = "({$i->context->sql})";
344
                            $params = array_merge($params, $i->context->params);
345
                        }else{
346 1
                            $stubs[]='?';
347 1
                            $params[] = $i;
348
                        }
349 1
                    }
350 1
                    $stubs = implode(',', $stubs);
351 1
                    $exprs[] = "$k $op ($stubs)";
352
                }
353 17
            }else if($op == 'BETWEEN'){
354 2
                $cond = "$k BETWEEN";
355 2 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...
356
                    $cond = "$cond ".strval($var[0]);
357 2
                }elseif($var[0] instanceof BasicRule){
358 1
                    $cond = "$cond ({$var[0]->context->sql})";
359 1
                    $params = array_merge($params, $var[0]->context->params);
360 1
                }else{
361 1
                    $cond = "$cond ?";
362 1
                    $params[] = $var[0];
363
                }
364 2 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...
365 1
                    $cond = "$cond AND ".strval($var[1]);
366 2
                }elseif($var[1] instanceof BasicRule){
367 1
                    $cond = "$cond AND ({$var[1]->context->sql})";
368 1
                    $params = array_merge($params, $var[1]->context->params);
369 1
                }else{
370
                    $cond = "$cond AND ?";
371
                    $params[] = $var[1];
372
                }
373 2
                $exprs[] = $cond;
374 2
            }else{
375 17
                if(is_a($var, Raw::class)){
376 1
                    $exprs[] = "$k $op ".strval($var);
377 17
                }elseif($var instanceof BasicRule){
378
                    $exprs[] = "$k $op {$var->context->sql}";
379
                    $params = array_merge($params, $var->context->params);
380
                }else{
381 17
                    $exprs[] = "$k $op ?";
382 17
                    $params[] = $var;
383
                }
384
            }
385 17
        }
386
387 17
        self::condition($context, $prefix, implode(' AND ', $exprs), $params);
388 17
    }
389 30
    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...
390 30
        if(!empty($expr)){
391 30
            $expr = "($expr)";
392 30
            if($args){
393
                //因为PDO不支持绑定数组变量, 这里需要手动展开数组
394
                //也就是说把 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...
395 29
                $cutted = null;
396 29
                $cut = null;
397 29
                $toReplace = array();
398
399 29
                $newArgs=array();
400
                //找到所有数组对应的?符位置
401 29
                foreach ($args as $k =>$arg){
402 29
                    if(is_array($arg) || is_a($arg, Raw::class) || is_a($arg, BasicRule::class)){
403
404 2
                        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...
405 2
                            $cut = new NestedStringCut($expr);
406 2
                            $cutted = $cut->getText();
407 2
                        }
408
                        //找到第$k个?符
409 2
                        $pos = self::findQ($cutted, 0, $k);
410 2
                        $pos = $cut->mapPos($pos);
411 2
                        $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...
412
                            new \InvalidArgumentException("unmatched params and ? @ $expr"));
413
414 2
                        if(is_array($arg)){
415 1
                            $stubs = [];
416 1
                            foreach ($arg as $i){
417 1
                                if(is_a($i, Raw::class)){
418 1
                                    $stubs[] = strval($i);
419 1
                                }else{
420 1
                                    $stubs[] = '?';
421 1
                                    $newArgs[] = $i;
422
                                }
423 1
                            }
424 1
                            $stubs = implode(',', $stubs);
425 2 View Code Duplication
                        }elseif($arg instanceof BasicRule){
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...
426 1
                            $stubs = "({$arg->context->sql})";
427 1
                            $newArgs = array_merge($newArgs, $arg->context->params);
428 1
                        }else{
429 1
                            $stubs = strval($arg);
430
                        }
431 2
                        $toReplace[] = [$pos, $stubs];
432
433 2
                    }else{
434 29
                        $newArgs[]=$arg;
435
                    }
436 29
                }
437
438 29
                if(count($toReplace)){
439 2
                    $toReplace = array_reverse($toReplace);
440 2
                    foreach ($toReplace as $i){
441 2
                        list($pos, $v) = $i;
442 2
                        $expr = substr($expr, 0, $pos).$v.substr($expr, $pos+1);
443 2
                    }
444 2
                    $args = $newArgs;
445 2
                }
446 29
            }
447 30
            if($prefix){
448 30
                $context->appendSql($prefix.' '.$expr);
449 30
            }else{
450 3
                $context->appendSql($expr);
451
            }
452
453 30
            if($args){
454 29
                $context->appendParams($args);
455 29
            }
456 30
        }
457 30
    }
458
}
459
460
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...
461 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...
462 5
        $column = DB::wrap($column);
463 5
        $context->appendSql("GROUP BY $column");
464 5
    }
465
}
466
467
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...
468
{
469
    /**
470
     *
471
     * @param Context $context
472
     * @param $exceOnError boolean whether throw exceptions
473
     * @return ExecResult
474
     */
475 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...
476 25
        $st = $context->connection->prepare($context->sql);
477 25
        $success = $st->execute($context->params);
478 25
        return new ExecResult($success, $context->connection, $st);
479
    }
480
    /**
481
     *
482
     * @param Context $context
483
     * @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...
484
     * @return false|array
485
     */
486 28
    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...
487
488 28
        $st = $context->connection->prepare($context->sql);
489 28
        if($st->execute($context->params)){
490
            $res = $st->fetchAll(\PDO::FETCH_ASSOC);
491
            if ($dictAs){
492
                $dict= [];
493
                foreach ($res as $i){
494
                    $dict[$i[$dictAs]]=$i;
495
                }
496
                return $context->handleResult($dict);
497
            }
498
            return $context->handleResult($res);
499
        }else{
500 28
            return false;
501
        }
502
    }
503
504
    /**
505
     * @param Context $context
506
     * @return int|false
507
     */
508
    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...
509
510
        $found = [];
511
        if(!preg_match('/\bselect\b/i', $context->sql, $found, PREG_OFFSET_CAPTURE) ||
512
            count($found)==0){
513
            \PhpBoot\abort(new \PDOException("can not use count(*) without select"));
514
        }
515
        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...
516
        $columnBegin = $columnBegin + strlen('select')+1;
517
518
        $columnEnd = 0;
519
        $found = [];
520
        if(!preg_match('/\bfrom\b/i', $context->sql, $found, PREG_OFFSET_CAPTURE) ||
521
            count($found)==0){
522
            $columnEnd = strlen($context->sql);
523
        }else{
524
            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...
525
        }
526
        $sql = substr($context->sql, 0, $columnBegin);
527
        $sql .= ' COUNT(*) as `count` ';
528
        $sql .= substr($context->sql, $columnEnd);
529
530
        $st = $context->connection->prepare($sql);
531
        if($st->execute($context->params)){
532
            $res = $st->fetchAll(\PDO::FETCH_ASSOC);
533
            return $res[0]['count'];
534
        }else{
535
            return false;
536
        }
537
538
    }
539
}
540
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...
541
{
542 1
    public function set($context, $column, $value){
543 1
        if(is_string($column)){
544 1
            $this->setExpr($context, $column, $value);
545 1
        }else{
546 1
            $this->setArgs($context, $column);
547
        }
548 1
    }
549
550 1
    public function setExpr($context, $expr, $args){
551 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...
552 1
        if($this->first){
553 1
            $this->first = false;
554 1
            $prefix = 'ON DUPLICATE KEY UPDATE ';
555 1
        }else{
556
            $prefix = ',';
557
        }
558
559 1
        $context->appendSql("$prefix$expr",$prefix == 'ON DUPLICATE KEY UPDATE ');
560 1
        $context->appendParams($args);
561
562 1
    }
563 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...
564 1
        $set = [];
565 1
        $params = [];
566 1
        foreach ($values as $k=>$v){
567 1
            $k = DB::wrap($k);
568 1
            if(is_a($v, Raw::class)){//直接拼接sql,不需要转义
569 1
                $set[]= "$k=".$v->get();
570 1
            }else{
571
                $set[]= "$k=?";
572
                $params[]=$v;
573
            }
574 1
        }
575 1
        if($this->first){
576 1
            $this->first = false;
577 1
            $context->appendSql('ON DUPLICATE KEY UPDATE '.implode(',', $set));
578 1
            $context->appendParams($params);
579 1
        }else{
580
            $context->appendSql(','.implode(',', $set),false);
581
            $context->appendParams($params);
582
        }
583 1
    }
584
    private $first=true;
585
}
586