1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Author: Nil Portugués Calderó <[email protected]> |
4
|
|
|
* Date: 12/23/14 |
5
|
|
|
* Time: 1:23 PM. |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace NilPortugues\Sql\QueryFormatter\Tokenizer\Parser; |
12
|
|
|
|
13
|
|
|
use NilPortugues\Sql\QueryFormatter\Tokenizer\Tokenizer; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Class Quoted. |
17
|
|
|
*/ |
18
|
|
|
final class Quoted |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* @param Tokenizer $tokenizer |
22
|
|
|
* @param string $string |
23
|
|
|
*/ |
24
|
|
|
public static function isQuoted(Tokenizer $tokenizer, $string) |
25
|
|
|
{ |
26
|
|
|
if (!$tokenizer->getNextToken() && self::isQuotedString($string)) { |
27
|
|
|
$tokenizer->setNextToken(self::getQuotedString($string)); |
28
|
|
|
} |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @param string $string |
33
|
|
|
* |
34
|
|
|
* @return bool |
35
|
|
|
*/ |
36
|
|
|
protected static function isQuotedString($string) |
37
|
|
|
{ |
38
|
|
|
return !empty($string[0]) && ($string[0] === '"' || $string[0] === '\'' || $string[0] === '`' || $string[0] === '['); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @param string $string |
43
|
|
|
* |
44
|
|
|
* @return array |
45
|
|
|
*/ |
46
|
|
|
protected static function getQuotedString($string) |
47
|
|
|
{ |
48
|
|
|
$tokenType = Tokenizer::TOKEN_TYPE_QUOTE; |
49
|
|
|
|
50
|
|
|
if (!empty($string[0]) && ($string[0] === '`' || $string[0] === '[')) { |
51
|
|
|
$tokenType = Tokenizer::TOKEN_TYPE_BACK_TICK_QUOTE; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
return [ |
55
|
|
|
Tokenizer::TOKEN_TYPE => $tokenType, |
56
|
|
|
Tokenizer::TOKEN_VALUE => self::wrapStringWithQuotes($string), |
57
|
|
|
]; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* This checks for the following patterns: |
62
|
|
|
* 1. backtick quoted string using `` to escape |
63
|
|
|
* 2. square bracket quoted string (SQL Server) using ]] to escape |
64
|
|
|
* 3. double quoted string using "" or \" to escape |
65
|
|
|
* 4. single quoted string using '' or \' to escape. |
66
|
|
|
* |
67
|
|
|
* @param string $string |
68
|
|
|
* |
69
|
|
|
* @return null |
70
|
|
|
*/ |
71
|
|
|
public static function wrapStringWithQuotes($string) |
72
|
|
|
{ |
73
|
|
|
$returnString = null; |
74
|
|
|
|
75
|
|
|
$regex = '/^(((`[^`]*($|`))+)|((\[[^\]]*($|\]))(\][^\]]*($|\]))*)|'. |
76
|
|
|
'(("[^"\\\\]*(?:\\\\.[^"\\\\]*)*("|$))+)|((\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*(\'|$))+))/s'; |
77
|
|
|
|
78
|
|
|
if (1 == \preg_match($regex, $string, $matches)) { |
79
|
|
|
$returnString = $matches[1]; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
return $returnString; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|