Completed
Push — master ( b7ef6a...58a002 )
by Kirill
03:12
created

Field::analyse()   B

Complexity

Conditions 9
Paths 16

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 9

Importance

Changes 0
Metric Value
dl 0
loc 39
ccs 23
cts 23
cp 1
rs 7.7404
c 0
b 0
f 0
cc 9
nc 16
nop 1
crap 9
1
<?php
2
/**
3
 * This file is part of Hydrogen package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
declare(strict_types=1);
9
10
namespace RDS\Hydrogen\Criteria\Common;
11
12
use Doctrine\ORM\Query\Lexer;
13
14
/**
15
 * Class Field
16
 */
17
class Field implements FieldInterface, \IteratorAggregate
18
{
19
    /**
20
     * Inherit value delimiter
21
     */
22
    public const DEEP_DELIMITER = '.';
23
24
    /**
25
     * Prefix using for disable aliasing field
26
     */
27
    public const NON_ALIASED_PREFIX = ':';
28
29
    /**
30
     * @var array|string[]
31
     */
32
    private $chunks = [];
33
34
    /**
35
     * @var bool
36
     */
37
    private $prefixed = true;
38
39
    /**
40
     * @var string
41
     */
42
    private $wrapper = '';
43
44
    /**
45
     * Field constructor.
46
     * @param string $query
47
     */
48 77
    public function __construct(string $query)
49
    {
50 77
        \assert(\strlen(\trim($query)) > 0);
51
52 77
        $this->analyseAndFill($query);
53
54 77
        if (\count($this->chunks) === 0) {
55 1
            $this->prefixed = false;
56
        }
57 77
    }
58
59
    /**
60
     * @param string $query
61
     * @return void
62
     */
63 77
    private function analyseAndFill(string $query): void
64
    {
65 77
        $analyzed = $this->analyse(new Lexer($query));
66 77
        $haystack = 0;
67
68 77
        foreach ($analyzed as $chunk) {
69 76
            $this->chunks[] = \ltrim($chunk, ':');
70 76
            $haystack += \strlen($chunk) + 1;
71
        }
72
73 77
        $before = \substr($query, 0, $analyzed->getReturn());
74 77
        $after  = \substr($query, $analyzed->getReturn() + \max(0, $haystack - 1));
75
76 77
        $this->wrapper = $before . '%s' . $after;
77 77
    }
78
79
    /**
80
     * @param Lexer $lexer
81
     * @return \Generator|string[]
82
     */
83 77
    private function analyse(Lexer $lexer): \Generator
84
    {
85 77
        [$offset, $keep] = [null, true];
0 ignored issues
show
Bug introduced by
The variable $offset seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
Bug introduced by
The variable $keep seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
86
87 77
        foreach ($this->lex($lexer) as $token => $lookahead) {
88 77
            switch ($token['type']) {
89 77
                case Lexer::T_OPEN_PARENTHESIS:
90 16
                    $keep = true;
91 16
                    break;
92
93 77
                case Lexer::T_INPUT_PARAMETER:
94 55
                    $this->prefixed = false;
95
96 38
                case Lexer::T_IDENTIFIER:
97 77
                    if ($lookahead['type'] === Lexer::T_OPEN_PARENTHESIS) {
98 5
                        $keep = false;
99
                    }
100
101 77
                    if ($keep) {
0 ignored issues
show
Bug introduced by
The variable $keep 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...
102 76
                        if ($offset === null) {
0 ignored issues
show
Bug introduced by
The variable $offset 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...
103 76
                            $offset = $token['position'];
104
                        }
105 76
                        $keep = false;
106 76
                        yield $token['value'];
107
                    }
108
109 77
                    break;
110
111 19
                case Lexer::T_DOT:
112 3
                    $keep = true;
113 3
                    break;
114
115
                default:
116 77
                    $keep = false;
117
            }
118
        }
119
120 77
        return (int)$offset;
121
    }
122
123
    /**
124
     * @param Lexer $lexer
125
     * @return \Generator
126
     */
127 77
    private function lex(Lexer $lexer): \Generator
128
    {
129 77
        while ($lexer->moveNext()) {
130 77
            if ($lexer->token) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $lexer->token of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
131 19
                yield $lexer->token => $lexer->lookahead;
132
            }
133
        }
134
135 77
        yield $lexer->token => $lexer->lookahead ?? ['type' => null, 'value' => null];
136 77
    }
137
138
    /**
139
     * @param string $query
140
     * @return Field
141
     */
142 11
    public static function new(string $query): self
143
    {
144 11
        return new static($query);
145
    }
146
147
    /**
148
     * @return string
149
     */
150 77
    public function getName(): string
151
    {
152 77
        return \implode(self::DEEP_DELIMITER, $this->chunks);
153
    }
154
155
    /**
156
     * @param string|null $alias
157
     * @return string
158
     */
159 76
    public function toString(string $alias = null): string
160
    {
161 76
        $value = $alias && $this->prefixed
0 ignored issues
show
Bug Best Practice introduced by
The expression $alias of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
162 31
            ? \implode('.', [$alias, $this->getName()])
163 76
            : $this->getName();
164
165 76
        return \sprintf($this->wrapper, $value);
166
    }
167
168
    /**
169
     * @return bool
170
     */
171 13
    public function isPrefixed(): bool
172
    {
173 13
        return $this->prefixed;
174
    }
175
176
    /**
177
     * @return string
178
     */
179 1
    public function __toString(): string
180
    {
181 1
        return $this->toString();
182
    }
183
184
    /**
185
     * @return iterable|Field[]
186
     */
187 4
    public function getIterator(): iterable
188
    {
189 4
        $lastOne = \count($this->chunks) - 1;
190
191 4
        foreach ($this->chunks as $i => $chunk) {
192 4
            $clone = clone $this;
193 4
            $clone->chunks = [$chunk];
194
195 4
            yield $lastOne === $i => $clone;
196
        }
197 4
    }
198
}
199