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.
Passed
Push — master ( 17036d...efc942 )
by cao
03:02
created

ValuesImpl   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 75
Duplicated Lines 22.67 %

Coupling/Cohesion

Components 0
Dependencies 3

Test Coverage

Coverage 98.15%

Importance

Changes 0
Metric Value
dl 17
loc 75
ccs 53
cts 54
cp 0.9815
rs 10
c 0
b 0
f 0
wmc 17
lcom 0
cbo 3

4 Methods

Rating   Name   Duplication   Size   Complexity  
B values() 9 24 4
B batchValues() 8 22 4
A pick() 0 9 3
B toSql() 0 16 6

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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 28
    public function __construct($success, $pdo, $st){
12 28
        $this->pdo = $pdo;
13 28
        $this->st = $st;
14 28
        $this->success = $success;
15 28
        $this->rows = $this->st->rowCount();
16 28
    }
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 8
    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 8
        $table = DB::wrap($table);
110 8
        $context->appendSql("INSERT INTO $table");
111 8
    }
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 $context, array $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 View Code Duplication
        if(array_keys($values) === range(0, count($values) - 1)){
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...
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 3
    static public function batchValues(Context $context, array $values)
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
147
    {
148 3
        $count = count($values);
149 3
        if($count == 0){
150
            return;
151
        }
152 3
        $keys = array_keys($values[0]);
153 3
        $row = implode(',', self::toSql(array_values($values[0])));
154 3 View Code Duplication
        if($keys === range(0, count($keys) - 1)){
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...
155
            //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...
156 2
            $context->appendSql("VALUES($row)");
157 2
        }else{
158
            //(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...
159
            $columns = implode(',', array_map(function($k){return DB::wrap($k);}, $keys));
160 1
            $context->appendSql("($columns) VALUES($row)",false);
161
        }
162 3
        for($i=1; $i<$count; $i++){
163 1
            $value = self::pick($keys, $values[$i]);
164 1
            $row = implode(',', self::toSql($value));
165 1
            $context->appendSql(", ($row)",false);
166 1
        }
167 3
    }
168
169 1
    static protected function pick(array $keys, array $values)
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
170
    {
171 1
        $res = [];
172 1
        foreach ($keys as $key){
173 1
            array_key_exists($key, $values) or \PhpBoot\abort("key $key not exist from the given array");
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...
174 1
            $res[$key] = $values[$key];
175 1
        }
176 1
        return $res;
177
    }
178 3
    static protected function toSql(array $values)
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
179
    {
180 3
        foreach ($values as &$v){
181 3
            if($v instanceof Raw){
182 3
                $v = $v->get();
183 3
            }elseif(is_bool($v)){
184 3
                $v = $v?'true':'false';
185 3
            }elseif(!in_array(gettype($v), ['integer', 'boolean', 'double', 'float'])){
186 3
                $v = (string)$v;
187 3
                $v = str_replace("\\", "\\\\", $v);
188 3
                $v = str_replace("'", "\\'", $v);
189 3
                $v = "'$v'";
190 3
            }
191 3
        }
192 3
        return $values;
193
    }
194
}
195
196
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...
197
{
198 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...
199 11
        $table = DB::wrap($table);
200 11
        $context->appendSql("UPDATE $table");
201 11
    }
202
}
203
204
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...
205
{
206 11
    public function set(Context $context, $expr, $args){
207 11
        if(is_string($expr)){
208
            return $this->setExpr($context, $expr, $args);
209
        }else{
210 11
            return $this->setArgs($context, $expr);
211
        }
212
    }
213
214
    public function setExpr(Context $context, $expr, $args){
215
        if($this->first){
216
            $this->first = false;
217
            $prefix = 'SET ';
218
        }else{
219
            $prefix = ',';
220
        }
221
222
        $context->appendSql("$prefix$expr",$prefix == 'SET ');
223
        $context->appendParams($args);
224
225
    }
226 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...
227 11
        $set = [];
228 11
        $params = [];
229 11
        foreach ($values as $k=>$v){
230 11
            $k = DB::wrap($k);
231 11
            if(is_a($v, Raw::class)){//直接拼接sql,不需要转义
232 1
                $set[]= "$k=".$v->get();
233 1
            }else{
234 11
                $set[]= "$k=?";
235 11
                $params[]=$v;
236
            }
237 11
        }
238 11
        if($this->first){
239 11
            $this->first = false;
240 11
            $context->appendSql('SET '.implode(',', $set));
241 11
            $context->appendParams($params);
242 11
        }else{
243
            $context->appendSql(','.implode(',', $set),false);
244
            $context->appendParams($params);
245
        }
246 11
    }
247
    private $first=true;
248
}
249
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...
250
{
251 7
    public function orderByArgs(Context $context, $orders){
252 7
        if(empty($orders)){
253
            return $this;
254
        }
255 7
        $params = array();
256 7
        foreach ($orders as $k=>$v){
257 7
            if(is_integer($k)){
258 6
                $params[] = DB::wrap($v);
259 6
            }else{
260 2
                $k = DB::wrap($k);
261
262 2
                $v = strtoupper($v);
263 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...
264
265 2
                $params[] = "$k $v";
266
            }
267 7
        }
268 7
        if($this->first){
269 7
            $this->first = false;
270 7
            $context->appendSql('ORDER BY '.implode(',', $params));
271 7
        }else{
272 1
            $context->appendSql(','.implode(',', $params),false);
273
        }
274 7
        return $this;
275
    }
276 7
    public function orderBy(Context $context, $column, $order=null){
277 7
        if(is_string($column)){
278 7
            if($order === null){
279 6
                $column = [$column];
280 6
            }else{
281 2
                $column = [$column=>$order];
282
            }
283 7
        }
284 7
        return $this->orderByArgs($context, $column);
285
286
287
    }
288
    private $first=true;
289
}
290
291
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...
292
{
293 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...
294 3
        $intSize = intval($size);
295 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...
296
            new \InvalidArgumentException("invalid params for limit($size)"));
297 3
        $context->appendSql("LIMIT $size");
298 3
    }
299 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...
300 1
        $intStart = intval($start);
301 1
        $intSize = intval($size);
302 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...
303
            new \InvalidArgumentException("invalid params for limit($start, $size)"));
304 1
        $context->appendSql("LIMIT $start,$size");
305 1
    }
306
}
307
308
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...
309
310 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...
311 2
        $found = strpos($str, '?', $offset);
312 2
        if($no == 0 || $found === false){
313 2
            return $found;
314
        }
315 1
        return self::findQ($str, $found+1, $no-1);
316
    }
317
318 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...
319 31
        if(empty($expr)){
320 1
            return;
321
        }
322 30
        if(is_callable($expr)){
323 3
            self::conditionClosure($context,$prefix, $expr);
324 30
        }elseif (is_string($expr)){
325 15
            self::condition($context, $prefix, $expr, $args);
326 15
        }else{
327 17
            self::conditionArgs($context, $prefix, $expr);
328
        }
329
330 30
    }
331
332 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...
333 3
        $context->appendSql($prefix.' (');
334 3
        $callback($context);
335 3
        $context->appendSql(')');
336 3
    }
337
    /**
338
     * find like Mongodb query glossary
339
     * whereArray(
340
     *      [
341
     *          'id'=>['>'=>1],
342
     *          'name'=>'cym',
343
     *      ]
344
     * )
345
     * 支持的操作符有
346
     * =    'id'=>['=' => 1]
347
     * >    'id'=>['>' => 1]
348
     * <    'id'=>['<' => 1]
349
     * <>   'id'=>['<>' => 1]
350
     * >=   'id'=>['>=' => 1]
351
     * <=   'id'=>['<=' => 1]
352
     * BETWEEN  'id'=>['BETWEEN' => [1 ,2]]
353
     * LIKE     'id'=>['LIKE' => '1%']
354
     * IN   'id'=>['IN' => [1,2,3]]
355
     * NOT IN   'id'=>['NOT IN' => [1,2,3]]
356
     * @return void
357
     */
358 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...
359 17
        if($args ===null){
360
            return ;
361
        }
362 17
        $exprs = array();
363 17
        $params = array();
364 17
        foreach ($args as $k => $v){
365 17
            $k = DB::wrap($k);
366 17
            if(!is_array($v)){
367 17
                $v = ['='=>$v];
368 17
            }
369
370 17
            $ops = ['=', '>', '<', '<>', '>=', '<=', 'IN', 'NOT IN', 'BETWEEN', 'LIKE'];
371 17
            $op = array_keys($v)[0];
372 17
            $op = strtoupper($op);
373
374 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...
375
                new \InvalidArgumentException("invalid param $op for whereArgs"));
376
377 17
            $var = array_values($v)[0];
378 17
            if($op == 'IN' || $op == 'NOT IN'){
379 2
                $stubs = [];
380
381 2
                if($var instanceof BasicRule){
382 1
                    $stubs = "({$var->context->sql})";
383 1
                    $params = array_merge($params, $var->context->params);
384 1
                    $exprs[] = "$k $op $stubs";
385 1
                }else{
386 1
                    foreach ($var as $i){
387 1
                        if(is_a($i, Raw::class)){
388 1
                            $stubs[]=strval($i);
389 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...
390
                            $stubs = "({$i->context->sql})";
391
                            $params = array_merge($params, $i->context->params);
392
                        }else{
393 1
                            $stubs[]='?';
394 1
                            $params[] = $i;
395
                        }
396 1
                    }
397 1
                    $stubs = implode(',', $stubs);
398 1
                    $exprs[] = "$k $op ($stubs)";
399
                }
400 17
            }else if($op == 'BETWEEN'){
401 2
                $cond = "$k BETWEEN";
402 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...
403
                    $cond = "$cond ".strval($var[0]);
404 2
                }elseif($var[0] instanceof BasicRule){
405 1
                    $cond = "$cond ({$var[0]->context->sql})";
406 1
                    $params = array_merge($params, $var[0]->context->params);
407 1
                }else{
408 1
                    $cond = "$cond ?";
409 1
                    $params[] = $var[0];
410
                }
411 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...
412 1
                    $cond = "$cond AND ".strval($var[1]);
413 2
                }elseif($var[1] instanceof BasicRule){
414 1
                    $cond = "$cond AND ({$var[1]->context->sql})";
415 1
                    $params = array_merge($params, $var[1]->context->params);
416 1
                }else{
417
                    $cond = "$cond AND ?";
418
                    $params[] = $var[1];
419
                }
420 2
                $exprs[] = $cond;
421 2
            }else{
422 17
                if(is_a($var, Raw::class)){
423 1
                    $exprs[] = "$k $op ".strval($var);
424 17
                }elseif($var instanceof BasicRule){
425
                    $exprs[] = "$k $op {$var->context->sql}";
426
                    $params = array_merge($params, $var->context->params);
427
                }else{
428 17
                    $exprs[] = "$k $op ?";
429 17
                    $params[] = $var;
430
                }
431
            }
432 17
        }
433
434 17
        self::condition($context, $prefix, implode(' AND ', $exprs), $params);
435 17
    }
436 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...
437 30
        if(!empty($expr)){
438 30
            $expr = "($expr)";
439 30
            if($args){
440
                //因为PDO不支持绑定数组变量, 这里需要手动展开数组
441
                //也就是说把 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...
442 29
                $cutted = null;
443 29
                $cut = null;
444 29
                $toReplace = array();
445
446 29
                $newArgs=array();
447
                //找到所有数组对应的?符位置
448 29
                foreach ($args as $k =>$arg){
449 29
                    if(is_array($arg) || is_a($arg, Raw::class) || is_a($arg, BasicRule::class)){
450
451 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...
452 2
                            $cut = new NestedStringCut($expr);
453 2
                            $cutted = $cut->getText();
454 2
                        }
455
                        //找到第$k个?符
456 2
                        $pos = self::findQ($cutted, 0, $k);
457 2
                        $pos = $cut->mapPos($pos);
458 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...
459
                            new \InvalidArgumentException("unmatched params and ? @ $expr"));
460
461 2
                        if(is_array($arg)){
462 1
                            $stubs = [];
463 1
                            foreach ($arg as $i){
464 1
                                if(is_a($i, Raw::class)){
465 1
                                    $stubs[] = strval($i);
466 1
                                }else{
467 1
                                    $stubs[] = '?';
468 1
                                    $newArgs[] = $i;
469
                                }
470 1
                            }
471 1
                            $stubs = implode(',', $stubs);
472 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...
473 1
                            $stubs = "({$arg->context->sql})";
474 1
                            $newArgs = array_merge($newArgs, $arg->context->params);
475 1
                        }else{
476 1
                            $stubs = strval($arg);
477
                        }
478 2
                        $toReplace[] = [$pos, $stubs];
479
480 2
                    }else{
481 29
                        $newArgs[]=$arg;
482
                    }
483 29
                }
484
485 29
                if(count($toReplace)){
486 2
                    $toReplace = array_reverse($toReplace);
487 2
                    foreach ($toReplace as $i){
488 2
                        list($pos, $v) = $i;
489 2
                        $expr = substr($expr, 0, $pos).$v.substr($expr, $pos+1);
490 2
                    }
491 2
                    $args = $newArgs;
492 2
                }
493 29
            }
494 30
            if($prefix){
495 30
                $context->appendSql($prefix.' '.$expr);
496 30
            }else{
497 3
                $context->appendSql($expr);
498
            }
499
500 30
            if($args){
501 29
                $context->appendParams($args);
502 29
            }
503 30
        }
504 30
    }
505
}
506
507
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...
508 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...
509 5
        $column = DB::wrap($column);
510 5
        $context->appendSql("GROUP BY $column");
511 5
    }
512
}
513
514
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...
515
{
516
    /**
517
     *
518
     * @param Context $context
519
     * @param $exceOnError boolean whether throw exceptions
520
     * @return ExecResult
521
     */
522 28
    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...
523 28
        $st = $context->connection->prepare($context->sql);
524 28
        $success = $st->execute($context->params);
525 28
        return new ExecResult($success, $context->connection, $st);
526
    }
527
    /**
528
     *
529
     * @param Context $context
530
     * @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...
531
     * @return false|array
532
     */
533 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...
534
535 28
        $st = $context->connection->prepare($context->sql);
536 28
        if($st->execute($context->params)){
537
            $res = $st->fetchAll(\PDO::FETCH_ASSOC);
538
            if ($dictAs){
539
                $dict= [];
540
                foreach ($res as $i){
541
                    $dict[$i[$dictAs]]=$i;
542
                }
543
                return $context->handleResult($dict);
544
            }
545
            return $context->handleResult($res);
546
        }else{
547 28
            return false;
548
        }
549
    }
550
551
    /**
552
     * @param Context $context
553
     * @return int|false
554
     */
555
    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...
556
557
        $found = [];
558
        if(!preg_match('/\bselect\b/i', $context->sql, $found, PREG_OFFSET_CAPTURE) ||
559
            count($found)==0){
560
            \PhpBoot\abort(new \PDOException("can not use count(*) without select"));
561
        }
562
        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...
563
        $columnBegin = $columnBegin + strlen('select')+1;
564
565
        $columnEnd = 0;
566
        $found = [];
567
        if(!preg_match('/\bfrom\b/i', $context->sql, $found, PREG_OFFSET_CAPTURE) ||
568
            count($found)==0){
569
            $columnEnd = strlen($context->sql);
570
        }else{
571
            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...
572
        }
573
        $sql = substr($context->sql, 0, $columnBegin);
574
        $sql .= ' COUNT(*) as `count` ';
575
        $sql .= substr($context->sql, $columnEnd);
576
577
        $st = $context->connection->prepare($sql);
578
        if($st->execute($context->params)){
579
            $res = $st->fetchAll(\PDO::FETCH_ASSOC);
580
            return intval($res[0]['count']);
581
        }else{
582
            return false;
583
        }
584
585
    }
586
}
587
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...
588
{
589 1
    public function set($context, $column, $value){
590 1
        if(is_string($column)){
591 1
            $this->setExpr($context, $column, $value);
592 1
        }else{
593 1
            $this->setArgs($context, $column);
594
        }
595 1
    }
596
597 1
    public function setExpr($context, $expr, $args){
598 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...
599 1
        if($this->first){
600 1
            $this->first = false;
601 1
            $prefix = 'ON DUPLICATE KEY UPDATE ';
602 1
        }else{
603
            $prefix = ',';
604
        }
605
606 1
        $context->appendSql("$prefix$expr",$prefix == 'ON DUPLICATE KEY UPDATE ');
607 1
        $context->appendParams($args);
608
609 1
    }
610 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...
611 1
        $set = [];
612 1
        $params = [];
613 1
        foreach ($values as $k=>$v){
614 1
            $k = DB::wrap($k);
615 1
            if(is_a($v, Raw::class)){//直接拼接sql,不需要转义
616 1
                $set[]= "$k=".$v->get();
617 1
            }else{
618
                $set[]= "$k=?";
619
                $params[]=$v;
620
            }
621 1
        }
622 1
        if($this->first){
623 1
            $this->first = false;
624 1
            $context->appendSql('ON DUPLICATE KEY UPDATE '.implode(',', $set));
625 1
            $context->appendParams($params);
626 1
        }else{
627
            $context->appendSql(','.implode(',', $set),false);
628
            $context->appendParams($params);
629
        }
630 1
    }
631
    private $first=true;
632
}
633