File: SqlPreprocessor.php

package info (click to toggle)
php-nette 2.4-20160731-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 3,208 kB
  • ctags: 7,552
  • sloc: php: 31,410; makefile: 6
file content (264 lines) | stat: -rw-r--r-- 7,409 bytes parent folder | download
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
<?php

/**
 * This file is part of the Nette Framework (https://nette.org)
 * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
 */

namespace Nette\Database;

use Nette;


/**
 * SQL preprocessor.
 */
class SqlPreprocessor
{
	use Nette\SmartObject;

	/** @var Connection */
	private $connection;

	/** @var ISupplementalDriver */
	private $driver;

	/** @var array of input parameters */
	private $params;

	/** @var array of parameters to be processed by PDO */
	private $remaining;

	/** @var int */
	private $counter;

	/** @var string values|set|and|order */
	private $arrayMode;


	public function __construct(Connection $connection)
	{
		$this->connection = $connection;
		$this->driver = $connection->getSupplementalDriver();
	}


	/**
	 * @param  array
	 * @return array of [sql, params]
	 */
	public function process($params)
	{
		$this->params = $params;
		$this->counter = 0;
		$prev = -1;
		$this->remaining = [];
		$this->arrayMode = NULL;
		$res = [];

		while ($this->counter < count($params)) {
			$param = $params[$this->counter++];

			if (($this->counter === 2 && count($params) === 2) || !is_scalar($param)) {
				$res[] = $this->formatValue($param, 'auto');
				$this->arrayMode = NULL;

			} elseif (is_string($param) && $this->counter > $prev + 1) {
				$prev = $this->counter;
				$this->arrayMode = NULL;
				$res[] = Nette\Utils\Strings::replace(
					$param,
					'~\'[^\']*+\'|"[^"]*+"|\?[a-z]*|^\s*+(?:INSERT|REPLACE)\b|\b(?:SET|WHERE|HAVING|ORDER BY|GROUP BY|KEY UPDATE)(?=\s*\z|\s*\?)|/\*.*?\*/|--[^\n]*~si',
					[$this, 'callback']
				);
			} else {
				throw new Nette\InvalidArgumentException('There are more parameters than placeholders.');
			}
		}

		return [implode(' ', $res), $this->remaining];
	}


	/** @internal */
	public function callback($m)
	{
		$m = $m[0];
		if ($m[0] === '?') { // placeholder
			if ($this->counter >= count($this->params)) {
				throw new Nette\InvalidArgumentException('There are more placeholders than passed parameters.');
			}
			return $this->formatValue($this->params[$this->counter++], substr($m, 1) ?: 'auto');

		} elseif ($m[0] === "'" || $m[0] === '"' || $m[0] === '/' || $m[0] === '-') { // string or comment
			return $m;

		} else { // command
			static $modes = [
				'INSERT' => 'values',
				'REPLACE' => 'values',
				'KEY UPDATE' => 'set',
				'SET' => 'set',
				'WHERE' => 'and',
				'HAVING' => 'and',
				'ORDER BY' => 'order',
				'GROUP BY' => 'order',
			];
			$this->arrayMode = $modes[ltrim(strtoupper($m))];
			return $m;
		}
	}


	private function formatValue($value, $mode = NULL)
	{
		if (!$mode || $mode === 'auto') {
			if (is_string($value)) {
				if (strlen($value) > 20) {
					$this->remaining[] = $value;
					return '?';

				} else {
					return $this->connection->quote($value);
				}

			} elseif (is_int($value)) {
				return (string) $value;

			} elseif (is_float($value)) {
				return rtrim(rtrim(number_format($value, 10, '.', ''), '0'), '.');

			} elseif (is_bool($value)) {
				return $this->driver->formatBool($value);

			} elseif ($value === NULL) {
				return 'NULL';

			} elseif ($value instanceof Table\IRow) {
				return $value->getPrimary();

			} elseif ($value instanceof SqlLiteral) {
				$prep = clone $this;
				list($res, $params) = $prep->process(array_merge([$value->__toString()], $value->getParameters()));
				$this->remaining = array_merge($this->remaining, $params);
				return $res;

			} elseif ($value instanceof \DateTimeInterface) {
				return $this->driver->formatDateTime($value);

			} elseif ($value instanceof \DateInterval) {
				return $this->driver->formatDateInterval($value);

			} elseif (is_object($value) && method_exists($value, '__toString')) {
				return $this->formatValue((string) $value);

			} elseif (is_resource($value)) {
				$this->remaining[] = $value;
				return '?';
			}

		} elseif ($mode === 'name') {
			if (!is_string($value)) {
				$type = gettype($value);
				throw new Nette\InvalidArgumentException("Placeholder ?$mode expects string, $type given.");
			}
			return $this->delimite($value);
		}

		if ($value instanceof \Traversable && !$value instanceof Table\IRow) {
			$value = iterator_to_array($value);
		}

		if (is_array($value)) {
			$vx = $kx = [];
			if ($mode === 'auto') {
				$mode = $this->arrayMode;
			}

			if ($mode === 'values') { // (key, key, ...) VALUES (value, value, ...)
				if (array_key_exists(0, $value)) { // multi-insert
					foreach ($value[0] as $k => $v) {
						$kx[] = $this->delimite($k);
					}
					foreach ($value as $val) {
						$vx2 = [];
						foreach ($val as $v) {
							$vx2[] = $this->formatValue($v);
						}
						$vx[] = implode(', ', $vx2);
					}
					$select = $this->driver->isSupported(ISupplementalDriver::SUPPORT_MULTI_INSERT_AS_SELECT);
					return '(' . implode(', ', $kx) . ($select ? ') SELECT ' : ') VALUES (')
						. implode($select ? ' UNION ALL SELECT ' : '), (', $vx) . ($select ? '' : ')');
				}

				foreach ($value as $k => $v) {
					$kx[] = $this->delimite($k);
					$vx[] = $this->formatValue($v);
				}
				return '(' . implode(', ', $kx) . ') VALUES (' . implode(', ', $vx) . ')';

			} elseif (!$mode || $mode === 'set') {
				foreach ($value as $k => $v) {
					if (is_int($k)) { // value, value, ... OR (1, 2), (3, 4)
						$vx[] = is_array($v) ? '(' . $this->formatValue($v) . ')' : $this->formatValue($v);
					} elseif (substr($k, -1) === '=') { // key+=value, key-=value, ...
						$k2 = $this->delimite(substr($k, 0, -2));
						$vx[] = $k2 . '=' . $k2 . ' ' . substr($k, -2, 1) . ' ' . $this->formatValue($v);
					} else { // key=value, key=value, ...
						$vx[] = $this->delimite($k) . '=' . $this->formatValue($v);
					}
				}
				return implode(', ', $vx);

			} elseif ($mode === 'and' || $mode === 'or') { // (key [operator] value) AND ...
				foreach ($value as $k => $v) {
					if (is_int($k)) {
						$vx[] = $this->formatValue($v);
						continue;
					}
					list($k, $operator) = explode(' ', $k . ' ');
					$k = $this->delimite($k);
					if (is_array($v)) {
						if ($v) {
							$vx[] = $k . ' ' . ($operator ? $operator . ' ' : '') . 'IN (' . $this->formatValue(array_values($v)) . ')';
						} elseif ($operator === 'NOT') {
						} else {
							$vx[] = '1=0';
						}
					} else {
						$v = $this->formatValue($v);
						$vx[] = $k . ' ' . ($operator ?: ($v === 'NULL' ? 'IS' : '=')) . ' ' . $v;
					}
				}
				return $value ? '(' . implode(') ' . strtoupper($mode) . ' (', $vx) . ')' : '1=1';

			} elseif ($mode === 'order') { // key, key DESC, ...
				foreach ($value as $k => $v) {
					$vx[] = $this->delimite($k) . ($v > 0 ? '' : ' DESC');
				}
				return implode(', ', $vx);

			} else {
				throw new Nette\InvalidArgumentException("Unknown placeholder ?$mode.");
			}

		} elseif (in_array($mode, ['and', 'or', 'set', 'values', 'order'], TRUE)) {
			$type = gettype($value);
			throw new Nette\InvalidArgumentException("Placeholder ?$mode expects array or Traversable object, $type given.");

		} elseif ($mode && $mode !== 'auto') {
			throw new Nette\InvalidArgumentException("Unknown placeholder ?$mode.");

		} else {
			throw new Nette\InvalidArgumentException('Unexpected type of parameter: ' . (is_object($value) ? get_class($value) : gettype($value)));
		}
	}


	private function delimite($name)
	{
		return implode('.', array_map([$this->driver, 'delimite'], explode('.', $name)));
	}

}