Passed
Push — master ( 9dbdd9...d5a428 )
by Alexander
04:15
created

framework/db/SqlToken.php (4 issues)

1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db;
9
10
use yii\base\BaseObject;
11
12
/**
13
 * SqlToken represents SQL tokens produced by [[SqlTokenizer]] or its child classes.
14
 *
15
 * @property SqlToken[] $children Child tokens.
16
 * @property-read bool $hasChildren Whether the token has children. This property is read-only.
17
 * @property-read bool $isCollection Whether the token represents a collection of tokens. This property is
18
 * read-only.
19
 * @property-read string $sql SQL code. This property is read-only.
20
 *
21
 * @author Sergey Makinen <[email protected]>
22
 * @since 2.0.13
23
 */
24
class SqlToken extends BaseObject implements \ArrayAccess
25
{
26
    const TYPE_CODE = 0;
27
    const TYPE_STATEMENT = 1;
28
    const TYPE_TOKEN = 2;
29
    const TYPE_PARENTHESIS = 3;
30
    const TYPE_KEYWORD = 4;
31
    const TYPE_OPERATOR = 5;
32
    const TYPE_IDENTIFIER = 6;
33
    const TYPE_STRING_LITERAL = 7;
34
35
    /**
36
     * @var int token type. It has to be one of the following constants:
37
     *
38
     * - [[TYPE_CODE]]
39
     * - [[TYPE_STATEMENT]]
40
     * - [[TYPE_TOKEN]]
41
     * - [[TYPE_PARENTHESIS]]
42
     * - [[TYPE_KEYWORD]]
43
     * - [[TYPE_OPERATOR]]
44
     * - [[TYPE_IDENTIFIER]]
45
     * - [[TYPE_STRING_LITERAL]]
46
     */
47
    public $type = self::TYPE_TOKEN;
48
    /**
49
     * @var string|null token content.
50
     */
51
    public $content;
52
    /**
53
     * @var int original SQL token start position.
54
     */
55
    public $startOffset;
56
    /**
57
     * @var int original SQL token end position.
58
     */
59
    public $endOffset;
60
    /**
61
     * @var SqlToken parent token.
62
     */
63
    public $parent;
64
65
    /**
66
     * @var SqlToken[] token children.
67
     */
68
    private $_children = [];
69
70
71
    /**
72
     * Returns the SQL code representing the token.
73
     * @return string SQL code.
74
     */
75
    public function __toString()
76
    {
77
        return $this->getSql();
78
    }
79
80
    /**
81
     * Returns whether there is a child token at the specified offset.
82
     * This method is required by the SPL [[\ArrayAccess]] interface.
83
     * It is implicitly called when you use something like `isset($token[$offset])`.
84
     * @param int $offset child token offset.
85
     * @return bool whether the token exists.
86
     */
87 12
    public function offsetExists($offset)
88
    {
89 12
        return isset($this->_children[$this->calculateOffset($offset)]);
90
    }
91
92
    /**
93
     * Returns a child token at the specified offset.
94
     * This method is required by the SPL [[\ArrayAccess]] interface.
95
     * It is implicitly called when you use something like `$child = $token[$offset];`.
96
     * @param int $offset child token offset.
97
     * @return SqlToken|null the child token at the specified offset, `null` if there's no token.
98
     */
99 25
    public function offsetGet($offset)
100
    {
101 25
        $offset = $this->calculateOffset($offset);
102 25
        return isset($this->_children[$offset]) ? $this->_children[$offset] : null;
103
    }
104
105
    /**
106
     * Adds a child token to the token.
107
     * This method is required by the SPL [[\ArrayAccess]] interface.
108
     * It is implicitly called when you use something like `$token[$offset] = $child;`.
109
     * @param int|null $offset child token offset.
110
     * @param SqlToken $token token to be added.
111
     */
112 25
    public function offsetSet($offset, $token)
113
    {
114 25
        $token->parent = $this;
115 25
        if ($offset === null) {
116 25
            $this->_children[] = $token;
117
        } else {
118
            $this->_children[$this->calculateOffset($offset)] = $token;
119
        }
120 25
        $this->updateCollectionOffsets();
121 25
    }
122
123
    /**
124
     * Removes a child token at the specified offset.
125
     * This method is required by the SPL [[\ArrayAccess]] interface.
126
     * It is implicitly called when you use something like `unset($token[$offset])`.
127
     * @param int $offset child token offset.
128
     */
129 13
    public function offsetUnset($offset)
130
    {
131 13
        $offset = $this->calculateOffset($offset);
132 13
        if (isset($this->_children[$offset])) {
133 13
            array_splice($this->_children, $offset, 1);
134
        }
135 13
        $this->updateCollectionOffsets();
136 13
    }
137
138
    /**
139
     * Returns child tokens.
140
     * @return SqlToken[] child tokens.
141
     */
142 24
    public function getChildren()
143
    {
144 24
        return $this->_children;
145
    }
146
147
    /**
148
     * Sets a list of child tokens.
149
     * @param SqlToken[] $children child tokens.
150
     */
151
    public function setChildren($children)
152
    {
153
        $this->_children = [];
154
        foreach ($children as $child) {
155
            $child->parent = $this;
156
            $this->_children[] = $child;
157
        }
158
        $this->updateCollectionOffsets();
159
    }
160
161
    /**
162
     * Returns whether the token represents a collection of tokens.
163
     * @return bool whether the token represents a collection of tokens.
164
     */
165 25
    public function getIsCollection()
166
    {
167 25
        return in_array($this->type, [
168 25
            self::TYPE_CODE,
169 25
            self::TYPE_STATEMENT,
170 25
            self::TYPE_PARENTHESIS,
171 25
        ], true);
172
    }
173
174
    /**
175
     * Returns whether the token represents a collection of tokens and has non-zero number of children.
176
     * @return bool whether the token has children.
177
     */
178 25
    public function getHasChildren()
179
    {
180 25
        return $this->getIsCollection() && !empty($this->_children);
181
    }
182
183
    /**
184
     * Returns the SQL code representing the token.
185
     * @return string SQL code.
186
     */
187 15
    public function getSql()
188
    {
189 15
        $code = $this;
190 15
        while ($code->parent !== null) {
191 15
            $code = $code->parent;
192
        }
193
194 15
        return mb_substr($code->content, $this->startOffset, $this->endOffset - $this->startOffset, 'UTF-8');
0 ignored issues
show
It seems like $code->content can also be of type null; however, parameter $string of mb_substr() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

194
        return mb_substr(/** @scrutinizer ignore-type */ $code->content, $this->startOffset, $this->endOffset - $this->startOffset, 'UTF-8');
Loading history...
195
    }
196
197
    /**
198
     * Returns whether this token (including its children) matches the specified "pattern" SQL code.
199
     *
200
     * Usage Example:
201
     *
202
     * ```php
203
     * $patternToken = (new \yii\db\sqlite\SqlTokenizer('SELECT any FROM any'))->tokenize();
204
     * if ($sqlToken->matches($patternToken, 0, $firstMatchIndex, $lastMatchIndex)) {
205
     *     // ...
206
     * }
207
     * ```
208
     *
209
     * @param SqlToken $patternToken tokenized SQL code to match against. In addition to normal SQL, the
210
     * `any` keyword is supported which will match any number of keywords, identifiers, whitespaces.
211
     * @param int $offset token children offset to start lookup with.
212
     * @param int|null $firstMatchIndex token children offset where a successful match begins.
213
     * @param int|null $lastMatchIndex token children offset where a successful match ends.
214
     * @return bool whether this token matches the pattern SQL code.
215
     */
216 12
    public function matches(SqlToken $patternToken, $offset = 0, &$firstMatchIndex = null, &$lastMatchIndex = null)
217
    {
218 12
        if (!$patternToken->getHasChildren()) {
219
            return false;
220
        }
221
222 12
        $patternToken = $patternToken[0];
223 12
        return $this->tokensMatch($patternToken, $this, $offset, $firstMatchIndex, $lastMatchIndex);
0 ignored issues
show
It seems like $patternToken can also be of type null; however, parameter $patternToken of yii\db\SqlToken::tokensMatch() does only seem to accept yii\db\SqlToken, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

223
        return $this->tokensMatch(/** @scrutinizer ignore-type */ $patternToken, $this, $offset, $firstMatchIndex, $lastMatchIndex);
Loading history...
224
    }
225
226
    /**
227
     * Tests the given token to match the specified pattern token.
228
     * @param SqlToken $patternToken
229
     * @param SqlToken $token
230
     * @param int $offset
231
     * @param int|null $firstMatchIndex
232
     * @param int|null $lastMatchIndex
233
     * @return bool
234
     */
235 12
    private function tokensMatch(SqlToken $patternToken, SqlToken $token, $offset = 0, &$firstMatchIndex = null, &$lastMatchIndex = null)
236
    {
237
        if (
238 12
            $patternToken->getIsCollection() !== $token->getIsCollection()
239 12
            || (!$patternToken->getIsCollection() && $patternToken->content !== $token->content)
240
        ) {
241 12
            return false;
242
        }
243
244 12
        if ($patternToken->children === $token->children) {
245 12
            $firstMatchIndex = $lastMatchIndex = $offset;
246 12
            return true;
247
        }
248
249 12
        $firstMatchIndex = $lastMatchIndex = null;
250 12
        $wildcard = false;
251 12
        for ($index = 0, $count = count($patternToken->children); $index < $count; $index++) {
252
            // Here we iterate token by token with an exception of "any" that toggles
253
            // an iteration until we matched with a next pattern token or EOF.
254 12
            if ($patternToken[$index]->content === 'any') {
255 12
                $wildcard = true;
256 12
                continue;
257
            }
258
259 12
            for ($limit = $wildcard ? count($token->children) : $offset + 1; $offset < $limit; $offset++) {
260 12
                if (!$wildcard && !isset($token[$offset])) {
261
                    break;
262
                }
263
264 12
                if (!$this->tokensMatch($patternToken[$index], $token[$offset])) {
0 ignored issues
show
It seems like $token[$offset] can also be of type null; however, parameter $token of yii\db\SqlToken::tokensMatch() does only seem to accept yii\db\SqlToken, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

264
                if (!$this->tokensMatch($patternToken[$index], /** @scrutinizer ignore-type */ $token[$offset])) {
Loading history...
It seems like $patternToken[$index] can also be of type null; however, parameter $patternToken of yii\db\SqlToken::tokensMatch() does only seem to accept yii\db\SqlToken, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

264
                if (!$this->tokensMatch(/** @scrutinizer ignore-type */ $patternToken[$index], $token[$offset])) {
Loading history...
265 12
                    continue;
266
                }
267
268 12
                if ($firstMatchIndex === null) {
269 12
                    $firstMatchIndex = $offset;
270 12
                }
271
                $lastMatchIndex = $offset;
272 12
                $wildcard = false;
273
                $offset++;
274 12
                continue 2;
275 12
            }
276 12
277
            return false;
278
        }
279 12
280
        return true;
281
    }
282 12
283
    /**
284
     * Returns an absolute offset in the children array.
285
     * @param int $offset
286
     * @return int
287
     */
288
    private function calculateOffset($offset)
289
    {
290 25
        if ($offset >= 0) {
291
            return $offset;
292 25
        }
293 25
294
        return count($this->_children) + $offset;
295
    }
296 25
297
    /**
298
     * Updates token SQL code start and end offsets based on its children.
299
     */
300
    private function updateCollectionOffsets()
301
    {
302 25
        if (!empty($this->_children)) {
303
            $this->startOffset = reset($this->_children)->startOffset;
304 25
            $this->endOffset = end($this->_children)->endOffset;
305 25
        }
306 25
        if ($this->parent !== null) {
307
            $this->parent->updateCollectionOffsets();
308 25
        }
309 25
    }
310
}
311