Statement.php
1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
namespace ACP\Search\Helper\Sql;
use ACP\Search\Value;
use LogicException;
class Statement {
/**
* @var Value[]
*/
protected $values = [];
/**
* @var string
*/
protected $statement;
/**
* @var string
*/
protected $value_type;
/**
* @param string $statement
*/
public function __construct( $statement ) {
$this->statement = $statement;
}
/**
* @param Value $value
*
* @return $this
*/
public function bind_value( Value $value ) {
$this->values[] = $value;
return $this;
}
/**
* Prepare string for safe usage
* @return string
*/
public function prepare() {
global $wpdb;
if ( substr_count( $this->statement, '?' ) != count( $this->values ) ) {
throw new LogicException( 'Amount of parameters and variables must be the same.' );
}
$statement = $this->statement;
$values = [];
foreach ( $this->values as $value ) {
$type = $value->get_type() === Value::INT
? '%d'
: '%s';
$statement = substr_replace(
$statement,
$type,
strpos( $statement, '?' ),
1
);
$values[] = $value->get_value();
}
return $wpdb->prepare( $statement, $values );
}
}