Completed
Push — master ( e0dde8...a7d2aa )
by Carsten
09:47
created

SqlToken::tokensMatch()   C

Complexity

Conditions 13
Paths 12

Size

Total Lines 47
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 13.0085

Importance

Changes 0
Metric Value
dl 0
loc 47
ccs 26
cts 27
cp 0.963
rs 5.0999
c 0
b 0
f 0
cc 13
eloc 29
nc 12
nop 5
crap 13.0085

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Object;
11
12
/**
13
 * SqlToken represents SQL tokens produced by [[SqlTokenizer]] or its child classes.
14
 *
15
 * @property SqlToken[] $children Child tokens.
16
 * @property bool $hasChildren Whether the token has children. This property is read-only.
17
 * @property bool $isCollection Whether the token represents a collection of tokens. This property is
18
 * read-only.
19
 * @property 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 Object 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 13
    public function offsetGet($offset)
100
    {
101 13
        $offset = $this->calculateOffset($offset);
102 13
        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 13
    public function offsetSet($offset, $token)
113
    {
114 13
        $token->parent = $this;
115 13
        if ($offset === null) {
116 13
            $this->_children[] = $token;
117
        } else {
118
            $this->_children[$this->calculateOffset($offset)] = $token;
119
        }
120 13
        $this->updateCollectionOffsets();
121 13
    }
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 1
    public function offsetUnset($offset)
130
    {
131 1
        $offset = $this->calculateOffset($offset);
132 1
        if (isset($this->_children[$offset])) {
133 1
            array_splice($this->_children, $offset, 1);
134
        }
135 1
        $this->updateCollectionOffsets();
136 1
    }
137
138
    /**
139
     * Returns child tokens.
140
     * @return SqlToken[] child tokens.
141
     */
142 12
    public function getChildren()
143
    {
144 12
        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 13
    public function getIsCollection()
166
    {
167 13
        return in_array($this->type, [
168 13
            self::TYPE_CODE,
169 13
            self::TYPE_STATEMENT,
170 13
            self::TYPE_PARENTHESIS,
171 13
        ], 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 13
    public function getHasChildren()
179
    {
180 13
        return $this->getIsCollection() && !empty($this->_children);
181
    }
182
183
    /**
184
     * Returns the SQL code representing the token.
185
     * @return string SQL code.
186
     */
187 3
    public function getSql()
188
    {
189 3
        $code = $this;
190 3
        while ($code->parent !== null) {
191 3
            $code = $code->parent;
192
        }
193 3
        return mb_substr($code->content, $this->startOffset, $this->endOffset - $this->startOffset, 'UTF-8');
194
    }
195
196
    /**
197
     * Returns whether this token (including its children) matches the specified "pattern" SQL code.
198
     *
199
     * Usage Example:
200
     *
201
     * ```php
202
     * $patternToken = (new \yii\db\sqlite\SqlTokenizer('SELECT any FROM any'))->tokenize();
203
     * if ($sqlToken->matches($patternToken, 0, $firstMatchIndex, $lastMatchIndex)) {
204
     *     // ...
205
     * }
206
     * ```
207
     *
208
     * @param SqlToken $patternToken tokenized SQL code to match against. In addition to normal SQL, the
209
     * `any` keyword is supported which will match any number of keywords, identifiers, whitespaces.
210
     * @param int $offset token children offset to start lookup with.
211
     * @param int|null $firstMatchIndex token children offset where a successful match begins.
212
     * @param int|null $lastMatchIndex token children offset where a successful match ends.
213
     * @return bool whether this token matches the pattern SQL code.
214
     */
215 12
    public function matches(SqlToken $patternToken, $offset = 0, &$firstMatchIndex = null, &$lastMatchIndex = null)
216
    {
217 12
        if (!$patternToken->getHasChildren()) {
218
            return false;
219
        }
220
221 12
        $patternToken = $patternToken[0];
222 12
        return $this->tokensMatch($patternToken, $this, $offset, $firstMatchIndex, $lastMatchIndex);
223
    }
224
225
    /**
226
     * Tests the given token to match the specified pattern token.
227
     * @param SqlToken $patternToken
228
     * @param SqlToken $token
229
     * @param int $offset
230
     * @param int|null $firstMatchIndex
231
     * @param int|null $lastMatchIndex
232
     * @return bool
233
     */
234 12
    private function tokensMatch(SqlToken $patternToken, SqlToken $token, $offset = 0, &$firstMatchIndex = null, &$lastMatchIndex = null)
235
    {
236
        if (
237 12
            $patternToken->getIsCollection() !== $token->getIsCollection()
238 12
            || (!$patternToken->getIsCollection() && $patternToken->content !== $token->content)
239
        ) {
240 12
            return false;
241
        }
242
243 12
        if ($patternToken->children === $token->children) {
244 12
            $firstMatchIndex = $lastMatchIndex = $offset;
245 12
            return true;
246
        }
247
248 12
        $firstMatchIndex = $lastMatchIndex = null;
249 12
        $wildcard = false;
250 12
        for ($index = 0, $count = count($patternToken->children); $index < $count; $index++) {
251
            // Here we iterate token by token with an exception of "any" that toggles
252
            // an iteration until we matched with a next pattern token or EOF.
253 12
            if ($patternToken[$index]->content === 'any') {
254 12
                $wildcard = true;
255 12
                continue;
256
            }
257
258 12
            for ($limit = $wildcard ? count($token->children) : $offset + 1; $offset < $limit; $offset++) {
259 12
                if (!$wildcard && !isset($token[$offset])) {
260
                    break;
261
                }
262
263 12
                if (!$this->tokensMatch($patternToken[$index], $token[$offset])) {
264 12
                    continue;
265
                }
266
267 12
                if ($firstMatchIndex === null) {
268 12
                    $firstMatchIndex = $offset;
269 12
                    $lastMatchIndex = $offset;
270
                } else {
271 12
                    $lastMatchIndex = $offset;
272
                }
273 12
                $wildcard = false;
274 12
                $offset++;
275 12
                continue 2;
276
            }
277 12
            return false;
278
        }
279 12
        return true;
280
    }
281
282
    /**
283
     * Returns an absolute offset in the children array.
284
     * @param int $offset
285
     * @return int
286
     */
287 13
    private function calculateOffset($offset)
288
    {
289 13
        if ($offset >= 0) {
290 13
            return $offset;
291
        }
292
293 13
        return count($this->_children) + $offset;
294
    }
295
296
    /**
297
     * Updates token SQL code start and end offsets based on its children.
298
     */
299 13
    private function updateCollectionOffsets()
300
    {
301 13
        if (!empty($this->_children)) {
302 13
            $this->startOffset = reset($this->_children)->startOffset;
303 13
            $this->endOffset = end($this->_children)->endOffset;
304
        }
305 13
        if ($this->parent !== null) {
306 13
            $this->parent->updateCollectionOffsets();
307
        }
308 13
    }
309
}
310