AbstractBuilder::getParam()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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