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 ( 91da2e...052e71 )
by cao
03:49
created

DB::insertInto()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 59 and the first side effect is on line 12.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
namespace PhpBoot\DB;
3
4
use PhpBoot\Application;
5
use PhpBoot\DB\rules\select\SelectRule;
6
use PhpBoot\DB\rules\insert\InsertRule;
7
use PhpBoot\DB\rules\update\UpdateRule;
8
use PhpBoot\DB\rules\delete\DeleteRule;
9
use PhpBoot\DB\rules\replace\ReplaceIntoRule;
10
use PhpBoot\Utils\Logger;
11
12 1
require_once __DIR__.'/rules/select.php';
13 1
require_once __DIR__.'/rules/insert.php';
14 1
require_once __DIR__.'/rules/update.php';
15 1
require_once __DIR__.'/rules/delete.php';
16 1
require_once __DIR__.'/rules/replace.php';
17
18
/**
19
 * 
20
 * How-to-use:
21
 * 
22
 * $db = new DB(...);
23
 * // 1. select
24
 * $res = $db->select('a, b')
25
 *      ->from('table')
26
 *      ->leftJoin('table1')->on('table.id=table1.id')
27
 *      ->where('a=?',1)
28
 *      ->groupBy('b')->having('sum(b)=?', 2)
29
 *      ->orderBy('c', Sql::ORDER_BY_ASC)
30
 *      ->limit(0,1)
31
 *      ->forUpdate()->of('d')
32
 *      ->get();
33
 * 
34
 * // 2. update
35
 * $rows = $db->update('table')
36
 *      ->set('a', 1)
37
 *      ->where('b=?', 2)
38
 *      ->orderBy('c', Sql::ORDER_BY_ASC)
39
 *      ->limit(1)
40
 *      ->exec($db)
41
 *      ->rows
42
 *      
43
 * // 3. insert
44
 * $newId = $db->insertInto('table')
45
 *      ->values(['a'=>1])
46
 *      ->exec($db)
47
 *      ->lastInsertId()
48
 *      
49
 * //4. delete
50
 * $rows = $db->deleteFrom('table')
51
 *      ->where('b=?', 2)
52
 *      ->orderBy('c', Sql::ORDER_BY_ASC)
53
 *      ->limit(1)
54
 *      ->exec($db)
55
 *      ->rows
56
 *      
57
 * @author caoym <[email protected]>
58
 */
59
class DB{
60
61
    /**
62
     * DB constructor.
63
     * @param Application $app
64
     * @param string $dsn @see \PDO
65
     * @param string $username @see \PDO
66
     * @param string $password @see \PDO
67
     * @param array $options @see \PDO
68
     */
69
70
    static public function connect(Application $app,
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
71
                                   $dsn,
72
                                  $username,
73
                                  $password,
74
                                  $options = [])
75
    {
76
        $options += [
77
            \PDO::ATTR_ERRMODE =>\PDO::ERRMODE_EXCEPTION,
78
            \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES'utf8';",
79
            \PDO::MYSQL_ATTR_FOUND_ROWS => true
80
        ];
81
82
        $connection = new \PDO($dsn, $username, $password, $options);
83
        return new DB($app, $connection);
84
    }
85
86 49
    public function __construct(Application $app, $connection)
87
    {
88 49
        $this->app = $app;
89 49
        $this->connection = $connection;
90 49
    }
91
92
    /**
93
     * select('column0,column1') => "SELECT column0,column1"
94
     *   
95
     * select('column0', 'column1') => "SELECT column0,column1"
96
     * 
97
     * @param string $column0
98
     * @return \PhpBoot\DB\rules\select\FromRule
99
     */
100 24
    function select($column0=null, $_=null){
0 ignored issues
show
Unused Code introduced by
The parameter $_ is not used and could be removed.

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

Loading history...
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
101 24
        $obj = new SelectRule(new Context($this->connection));
102 24
        if($column0 == null){
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $column0 of type string|null against null; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
103 5
            $args = ['*'];
104 24
        }elseif(is_array($column0)){
105 3
            $args = $column0;
106 3
        }else{
107 17
            $args = func_get_args();
108
        }
109 24
        foreach ($args as &$arg){
110 24
            $arg = DB::wrap($arg);
111 24
            if($arg == '*'){
112 12
                continue;
113
            }
114
115 24
        }
116 24
        return $obj->select(implode(',', $args));
117
    }
118
    /** 
119
     * insertInto('table') => "INSERT INTO table"
120
     * 
121
     * @param string $table
122
     * @return \PhpBoot\DB\rules\insert\ValuesRule
123
     */
124 5
    public function insertInto($table) {
125 5
        $obj = new InsertRule(new Context($this->connection));
126 5
        return $obj->insertInto($table);
127
    }
128
    /**
129
     * update('table') => "UPDATE table"
130
     * @param string $table
131
     * @return \PhpBoot\DB\rules\update\UpdateSetRule
132
     */
133 11
    public function update($table) {
134 11
        $obj = new UpdateRule(new Context($this->connection));
135 11
        return $obj->update($table);
136
    }
137
    
138
    /**
139
     * deleteFrom('table') => "DELETE FROM table"
140
     * @param string $table
141
     * @return \PhpBoot\DB\rules\basic\WhereRule
142
     */
143 7
    public function deleteFrom($table){
144 7
        $obj  =  new DeleteRule(new Context($this->connection));
145 7
        return $obj->deleteFrom($table);
146
    }
147
    /**
148
     * replaceInto('table') => "REPLACE INTO table"
149
     * @param string $table
150
     * @return \PhpBoot\DB\rules\replace\ValuesRule
151
     */
152 2
    public function replaceInto($table){
153 2
        $obj  =  new ReplaceIntoRule(new Context($this->connection));
154 2
        return $obj->replaceInto($table);
155
    }
156
157
    /**
158
     * @param callable $callback
159
     * @return mixed return
160
     * @throws \Exception
161
     */
162
    public function transaction(callable $callback)
163
    {
164
        if($this->inTransaction){
165
            return $callback($this);
166
        }
167
        $this->getConnection()->beginTransaction() or \PhpBoot\abort('beginTransaction failed');
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...
168
        $this->inTransaction = true;
169
        try{
170
            $res = $callback($this);
171
            $this->getConnection()->commit() or \PhpBoot\abort('commit failed');
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...
172
            return $res;
173
        }catch (\Exception $e){
174
            $this->getConnection()->rollBack();
175
            Logger::warning('commit failed with '.get_class($e).' '.$e->getMessage());
176
            throw $e;
177
        }
178
    }
179
    /**
180
     * @return \PDO
181
     */
182
    public function getConnection()
183
    {
184
        return $this->connection;
185
    }
186
    /**
187
	 * Splice sql use raw string(without escaping)
188
     * for example:
189
     * where('time>?', 'now()') => " WHERE time > 'now()' "
190
     * where('time>?', Sql::raw('now()')) => " WHERE time > now() "
191
     * @param string $str
192
     * @return Raw
193
     */
194 10
    static public function raw($str){
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
195 10
        return new Raw($str);
196
    }
197 50
    static public function wrap($value)
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
198
    {
199 50
        if($value instanceof Raw){
200 4
            return $value->get();
201
        }
202 50
        $value = trim($value);
203 50
        if ($value === '*') {
204 12
            return $value;
205
        }
206
207 49
        if(strpos($value, '.') !== false && !preg_match('/\\s+/', $value)){
208 1
            return $value;
209
        }
210 49
        return '`'.str_replace('`', '``', $value).'`';
211
    }
212
213
    /**
214
     * @return Application
215
     */
216 11
    public function getApp()
217
    {
218 11
        return $this->app;
219
    }
220
    const ORDER_BY_ASC ='ASC';
221
    const ORDER_BY_DESC ='DESC';
222
223
    /**
224
     * @var \PDO
225
     */
226
    protected $connection;
227
228
    /**
229
     * @var Application
230
     */
231
    protected $app;
232
233
    protected $inTransaction = false;
234
}
235