Completed
Push — master ( 467d47...6f2bb4 )
by Anton
14s
created

AbstractBuilder::setParameter()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 3
dl 0
loc 11
ccs 6
cts 6
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * Bluz Framework Component
4
 *
5
 * @copyright Bluz PHP Team
6
 * @link      https://github.com/bluzphp/framework
7
 */
8
9
declare(strict_types=1);
10
11
namespace Bluz\Db\Query;
12
13
use Bluz\Proxy\Db;
14
15
/**
16
 * Query Builders classes is responsible to dynamically create SQL queries
17
 * Based on Doctrine QueryBuilder code
18
 *
19
 * @package Bluz\Db\Query
20
 * @link    https://github.com/bluzphp/framework/wiki/Db-Query
21
 * @link    https://github.com/doctrine/dbal/blob/master/lib/Doctrine/DBAL/Query/QueryBuilder.php
22
 */
23
abstract class AbstractBuilder
24
{
25
    /**
26
     * @var array list of table aliases
27
     */
28
    protected $aliases = [];
29
30
    /**
31
     * @var array the query parameters
32
     */
33
    protected $params = [];
34
35
    /**
36
     * @var array the parameter type map of this query
37
     */
38
    protected $types = [];
39
40
    /**
41
     * @var string the complete SQL string for this query
42
     */
43
    protected $sql;
44
45
    /**
46
     * Execute this query using the bound parameters and their types
47
     *
48
     * @return integer|string|array
49
     */
50 8
    public function execute()
51
    {
52 8
        return Db::query($this->getSql(), $this->params, $this->types);
53
    }
54
55
    /**
56
     * Return the complete SQL string formed by the current specifications
57
     *
58
     * Example
59
     * <code>
60
     *     $sb = new SelectBuilder();
61
     *     $sb
62
     *         ->select('u')
63
     *         ->from('User', 'u');
64
     *     echo $qb->getSql(); // SELECT u FROM User u
65
     * </code>
66
     *
67
     * @return string The SQL query string
68
     */
69
    abstract public function getSql() : string;
70
71
    /**
72
     * Return the complete SQL string formed for use
73
     *
74
     * Example
75
     * <code>
76
     *     $sb = new SelectBuilder();
77
     *     $sb
78
     *         ->select('u')
79
     *         ->from('User', 'u')
80
     *         ->where('id = ?', 42);
81
     *     echo $qb->getQuery(); // SELECT u FROM User u WHERE id = "42"
82
     * </code>
83
     *
84
     * @return string
85
     */
86 7
    public function getQuery() : string
87
    {
88 7
        $sql = $this->getSql();
89
90 7
        $sql = str_replace(['%', '?'], ['%%', '"%s"'], $sql);
91
92
        // replace mask by data
93 7
        return vsprintf($sql, $this->getParams());
94
    }
95
96
    /**
97
     * Gets a (previously set) query parameter of the query being constructed
98
     *
99
     * @param  mixed $key The key (index or name) of the bound parameter
100
     *
101
     * @return mixed The value of the bound parameter.
102
     */
103 1
    public function getParam($key)
104
    {
105 1
        return $this->params[$key] ?? null;
106
    }
107
108
    /**
109
     * Sets a query parameter for the query being constructed
110
     *
111
     * Example
112
     * <code>
113
     *     $sb = new SelectBuilder();
114
     *     $sb
115
     *         ->select('u')
116
     *         ->from('users', 'u')
117
     *         ->where('u.id = :user_id')
118
     *         ->setParameter(':user_id', 1);
119
     * </code>
120
     *
121
     * @param  string|int|null $key   The parameter position or name
122
     * @param  mixed      $value The parameter value
123
     * @param  integer    $type  PDO::PARAM_*
124
     *
125
     * @return self
126
     */
127 9
    public function setParam($key, $value, $type = \PDO::PARAM_STR)
128
    {
129 9
        if (null === $key) {
130 9
            $key = count($this->params);
131
        }
132
133 9
        $this->params[$key] = $value;
134 9
        $this->types[$key] = $type;
135
136 9
        return $this;
137
    }
138
139
    /**
140
     * Gets all defined query parameters for the query being constructed
141
     *
142
     * @return array The currently defined query parameters
143
     */
144 7
    public function getParams() : array
145
    {
146 7
        return $this->params;
147
    }
148
149
    /**
150
     * Sets a collection of query parameters for the query being constructed
151
     *
152
     * Example
153
     * <code>
154
     *     $sb = new SelectBuilder();
155
     *     $sb
156
     *         ->select('u')
157
     *         ->from('users', 'u')
158
     *         ->where('u.id = :user_id1 OR u.id = :user_id2')
159
     *         ->setParameters([
160
     *             ':user_id1' => 1,
161
     *             ':user_id2' => 2
162
     *         ]);
163
     * </code>
164
     *
165
     * @param  array $params The query parameters to set
166
     * @param  array $types  The query parameters types to set
167
     *
168
     * @return self
169
     */
170 1
    public function setParams(array $params, array $types = [])
171
    {
172 1
        $this->types = $types;
173 1
        $this->params = $params;
174
175 1
        return $this;
176
    }
177
178
    /**
179
     * Prepare condition
180
     *
181
     * <code>
182
     *     $builder->prepareCondition("WHERE id IN (?)", [..,..]);
183
     * </code>
184
     *
185
     * @param  array $args
186
     *
187
     * @return string
188
     */
189 9
    protected function prepareCondition(array $args = []) : string
190
    {
191 9
        $condition = array_shift($args);
192 9
        foreach ($args as &$value) {
193 9
            if (is_array($value)) {
194 1
                $replace = implode(',', array_fill(0, count($value), ':REPLACE:'));
195 1
                $condition = preg_replace('/\?/', $replace, $condition, 1);
196 1
                foreach ($value as $part) {
197 1
                    $this->setParam(null, $part);
198
                }
199
            } else {
200 9
                $this->setParam(null, $value);
201
            }
202
        }
203 9
        unset($value);
204
205 9
        $condition = preg_replace('/(\:REPLACE\:)/', '?', $condition);
206
207 9
        return $condition;
208
    }
209
210
    /**
211
     * Gets a string representation of this QueryBuilder which corresponds to
212
     * the final SQL query being constructed.
213
     *
214
     * @return string The string representation of this QueryBuilder.
215
     */
216 1
    public function __toString()
217
    {
218 1
        return $this->getSql();
219
    }
220
}
221