PositionCalculator::findPositionWithinString()   F
last analyzed

Complexity

Conditions 24
Paths 642

Size

Total Lines 56
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 56
rs 3.5714
cc 24
eloc 31
nc 642
nop 3

How to fix   Long Method    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
/**
4
 * position-calculator.php.
5
 *
6
 * This file implements the calculator for the position elements of
7
 * the output of the PHPSQLParser.
8
 *
9
 * Copyright (c) 2010-2012, Justin Swanhart
10
 * with contributions by André Rothe <[email protected], [email protected]>
11
 *
12
 * All rights reserved.
13
 *
14
 * Redistribution and use in source and binary forms, with or without modification,
15
 * are permitted provided that the following conditions are met:
16
 *
17
 *   * Redistributions of source code must retain the above copyright notice,
18
 *     this list of conditions and the following disclaimer.
19
 *   * Redistributions in binary form must reproduce the above copyright notice,
20
 *     this list of conditions and the following disclaimer in the documentation
21
 *     and/or other materials provided with the distribution.
22
 *
23
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
24
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
26
 * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
28
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
29
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
32
 * DAMAGE.
33
 */
34
namespace SQLParser;
35
36
/**
37
 * This class calculates the positions
38
 * of base_expr within the original SQL statement.
39
 *
40
 * @author arothe
41
 */
42
class PositionCalculator extends PHPSQLParserUtils
43
{
44
    private static $allowedOnOperator = array("\t", "\n", "\r", ' ', ',', '(', ')', '_', "'", '"');
45
    private static $allowedOnOther = array("\t", "\n", "\r", ' ', ',', '(', ')', '<', '>', '*', '+', '-', '/', '|',
46
                                           '&', '=', '!', ';', );
47
48
    private function printPos($text, $sql, $charPos, $key, $parsed, $backtracking)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
Coding Style introduced by
printPos uses the super-global variable $_ENV which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
49
    {
50
        if (!isset($_ENV['DEBUG'])) {
51
            return;
52
        }
53
54
        $spaces = '';
55
        $caller = debug_backtrace();
56
        $i = 1;
57
        while ($caller[$i]['function'] === 'lookForBaseExpression') {
58
            $spaces .= '   ';
59
            ++$i;
60
        }
61
        $holdem = substr($sql, 0, $charPos).'^'.substr($sql, $charPos);
62
        echo $spaces.$text.' key:'.$key.'  parsed:'.$parsed.' back:'.serialize($backtracking).' '
63
                .$holdem."\n";
64
    }
65
66
    public function setPositionsWithinSQL($sql, $parsed)
67
    {
68
        $charPos = 0;
69
        $backtracking = array();
70
        $this->lookForBaseExpression($sql, $charPos, $parsed, 0, $backtracking);
71
72
        return $parsed;
73
    }
74
75
    private function findPositionWithinString($sql, $value, $expr_type)
76
    {
77
        $offset = 0;
78
        $ok = false;
0 ignored issues
show
Unused Code introduced by
$ok is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
79
        while (true) {
80
            $pos = strpos($sql, $value, $offset);
81
            if ($pos === false) {
82
                break;
83
            }
84
85
            $before = '';
86
            if ($pos > 0) {
87
                $before = $sql[$pos - 1];
88
            }
89
90
            $after = '';
91
            if (isset($sql[$pos + strlen($value)])) {
92
                $after = $sql[$pos + strlen($value)];
93
            }
94
95
            # if we have an operator, it should be surrounded by
96
            # whitespace, comma, parenthesis, digit or letter, end_of_string
97
            # an operator should not be surrounded by another operator
98
99
            if ($expr_type === 'operator') {
100
                $ok = ($before === '' || in_array($before, self::$allowedOnOperator, true))
101
                        || (strtolower($before) >= 'a' && strtolower($before) <= 'z')
102
                        || ($before >= '0' && $before <= '9');
103
                $ok = $ok
104
                        && ($after === '' || in_array($after, self::$allowedOnOperator, true)
105
                                || (strtolower($after) >= 'a' && strtolower($after) <= 'z')
106
                                || ($after >= '0' && $after <= '9') || ($after === '?') || ($after === '@'));
107
108
                if (!$ok) {
109
                    $offset = $pos + 1;
110
                    continue;
111
                }
112
113
                break;
114
            }
115
116
            # in all other cases we accept
117
            # whitespace, comma, operators, parenthesis and end_of_string
118
119
            $ok = ($before === '' || in_array($before, self::$allowedOnOther, true));
120
            $ok = $ok && ($after === '' || in_array($after, self::$allowedOnOther, true));
121
122
            if ($ok) {
123
                break;
124
            }
125
126
            $offset = $pos + 1;
127
        }
128
129
        return $pos;
0 ignored issues
show
Bug introduced by
The variable $pos does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
130
    }
131
132
    private function lookForBaseExpression($sql, &$charPos, &$parsed, $key, &$backtracking)
133
    {
134
        if (!is_numeric($key)) {
135
            if (($key === 'UNION' || $key === 'UNION ALL')
136
                    || ($key === 'expr_type' && $parsed === ExpressionType::EXPRESSION)
137
                    || ($key === 'expr_type' && $parsed === ExpressionType::SUBQUERY)
138
                    || ($key === 'expr_type' && $parsed === ExpressionType::BRACKET_EXPRESSION)
139
                    || ($key === 'expr_type' && $parsed === ExpressionType::TABLE_EXPRESSION)
140
                    || ($key === 'expr_type' && $parsed === ExpressionType::RECORD)
141
                    || ($key === 'expr_type' && $parsed === ExpressionType::IN_LIST)
142
                    || ($key === 'expr_type' && $parsed === ExpressionType::MATCH_ARGUMENTS)
143
                    || ($key === 'alias' && $parsed !== false)) {
144
                # we hold the current position and come back after the next base_expr
145
                # we do this, because the next base_expr contains the complete expression/subquery/record
146
                # and we have to look into it too
147
                $backtracking[] = $charPos;
148
            } elseif (($key === 'ref_clause' || $key === 'columns') && $parsed !== false) {
149
                # we hold the current position and come back after n base_expr(s)
150
                # there is an array of sub-elements before (!) the base_expr clause of the current element
151
                # so we go through the sub-elements and must come at the end
152
                $backtracking[] = $charPos;
153 View Code Duplication
                for ($i = 1; $i < count($parsed); ++$i) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
154
                    $backtracking[] = false; # backtracking only after n base_expr!
155
                }
156
            } elseif ($key === 'sub_tree' && $parsed !== false) {
157
                # we prevent wrong backtracking on subtrees (too much array_pop())
158
                # there is an array of sub-elements after(!) the base_expr clause of the current element
159
                # so we go through the sub-elements and must not come back at the end
160 View Code Duplication
                for ($i = 1; $i < count($parsed); ++$i) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
161
                    $backtracking[] = false;
162
                }
163
            } else {
164
                # move the current pos after the keyword
165
                # SELECT, WHERE, INSERT etc.
166
                if (in_array($key, parent::$reserved)) {
167
                    $charPos = stripos($sql, $key, $charPos);
168
                    $charPos += strlen($key);
169
                }
170
            }
171
        }
172
173
        if (!is_array($parsed)) {
174
            return;
175
        }
176
177
        foreach ($parsed as $key => $value) {
178
            if ($key === 'base_expr') {
179
180
                #$this->printPos("0", $sql, $charPos, $key, $value, $backtracking);
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
181
182
                $subject = substr($sql, $charPos);
183
                $pos = $this->findPositionWithinString($subject, $value,
184
                        isset($parsed['expr_type']) ? $parsed['expr_type'] : 'alias');
185
                if ($pos === false) {
186
                    throw new UnableToCalculatePositionException($value, $subject);
187
                }
188
189
                $parsed['position'] = $charPos + $pos;
190
                $charPos += $pos + strlen($value);
191
192
                #$this->printPos("1", $sql, $charPos, $key, $value, $backtracking);
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
193
194
                $oldPos = array_pop($backtracking);
195
                if (isset($oldPos) && $oldPos !== false) {
196
                    $charPos = $oldPos;
197
                }
198
199
                #$this->printPos("2", $sql, $charPos, $key, $value, $backtracking);
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
200
            } else {
201
                $this->lookForBaseExpression($sql, $charPos, $parsed[$key], $key, $backtracking);
202
            }
203
        }
204
    }
205
}
206