Passed
Push — master ( 0853ff...bcb7ae )
by Nikita
04:55
created

DollarExpansion::apply()   D

Complexity

Conditions 26
Paths 60

Size

Total Lines 92
Code Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 26
eloc 59
nc 60
nop 5
dl 0
loc 92
rs 4.5382
c 0
b 0
f 0

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
 * This file is part of PHP-Yacc 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 PhpYacc\Yacc\Macro;
11
12
use PhpYacc\Exception\ParseException;
13
use PhpYacc\Grammar\Context;
14
use PhpYacc\Yacc\MacroAbstract;
15
use PhpYacc\Yacc\Token;
16
17
/**
18
 * Class DollarExpansion.
19
 */
20
class DollarExpansion extends MacroAbstract
21
{
22
    const SEMVAL_LHS_TYPED = 1;
23
    const SEMVAL_LHS_UNTYPED = 2;
24
    const SEMVAL_RHS_TYPED = 3;
25
    const SEMVAL_RHS_UNTYPED = 4;
26
27
    /**
28
     * @param Context   $ctx
29
     * @param array     $symbols
30
     * @param \Iterator $tokens
31
     * @param int       $n
32
     * @param array     $attribute
33
     *
34
     * @throws ParseException
35
     * @throws \PhpYacc\Exception\LogicException
36
     *
37
     * @return \Generator
38
     */
39
    public function apply(Context $ctx, array $symbols, \Iterator $tokens, int $n, array $attribute): \Generator
40
    {
41
        $type = null;
0 ignored issues
show
Unused Code introduced by
$type 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...
42
        for ($tokens->rewind(); $tokens->valid(); $tokens->next()) {
43
            /** @var Token $token */
44
            $token = $tokens->current();
45
            switch ($token->getType()) {
46
                case Token::NAME:
47
                    $type = null;
48
                    $v = -1;
49
50
                    for ($i = 0; $i <= $n; $i++) {
51
                        if ($symbols[$i]->name === $token->getValue()) {
52
                            if ($v < 0) {
53
                                $v = $i;
54
                            } else {
55
                                throw new ParseException("Ambiguous semantic value reference for $token");
56
                            }
57
                        }
58
                    }
59
60
                    if ($v < 0) {
61
                        for ($i = 0; $i <= $n; $i++) {
62
                            if ($attribute[$i] === $token->getValue()) {
63
                                $v = $i;
64
                                break;
65
                            }
66
                        }
67
68
                        if ($token->getValue() === $attribute[$n + 1]) {
69
                            $v = 0;
70
                        }
71
                    }
72
73
                    if ($v >= 0) {
74
                        $token = new Token($v === 0 ? Token::DOLLAR : 0, $token->getValue(), $token->getLine(), $token->getFilename());
75
                        goto semval;
76
                    }
77
                    break;
78
79
                case Token::DOLLAR:
80
                    $type = null;
81
                    $token = self::next($tokens);
82
                    if ($token->getId() === '<') {
0 ignored issues
show
Deprecated Code introduced by
The method PhpYacc\Yacc\Token::getId() has been deprecated.

This method has been deprecated.

Loading history...
83
                        $token = self::next($tokens);
84
                        if ($token->getId() !== Token::NAME) {
0 ignored issues
show
Deprecated Code introduced by
The method PhpYacc\Yacc\Token::getId() has been deprecated.

This method has been deprecated.

Loading history...
85
                            throw ParseException::unexpected($token, Token::NAME);
86
                        }
87
                        $type = $ctx->intern($token->getValue());
88
                        $dump = self::next($tokens);
89
                        if ($dump->getId() !== '>') {
0 ignored issues
show
Deprecated Code introduced by
The method PhpYacc\Yacc\Token::getId() has been deprecated.

This method has been deprecated.

Loading history...
90
                            throw ParseException::unexpected($dump, '>');
91
                        }
92
                        $token = self::next($tokens);
93
                    }
94
95
                    if ($token->getType() === Token::DOLLAR) {
96
                        $v = 0;
97
                    } elseif ($token->getValue()[0] === '-') {
98
                        $token = self::next($tokens);
99
                        if ($token->getId() !== Token::NUMBER) {
0 ignored issues
show
Deprecated Code introduced by
The method PhpYacc\Yacc\Token::getId() has been deprecated.

This method has been deprecated.

Loading history...
100
                            throw ParseException::unexpected($token, Token::NUMBER);
101
                        }
102
                        $v = -1 * ((int) $token->getValue());
103
                    } else {
104
                        if ($token->getId() !== Token::NUMBER) {
0 ignored issues
show
Deprecated Code introduced by
The method PhpYacc\Yacc\Token::getId() has been deprecated.

This method has been deprecated.

Loading history...
105
                            throw new \RuntimeException('Number expected');
106
                        }
107
                        $v = (int) $token->getValue();
108
                        if ($v > $n) {
109
                            throw new \RuntimeException('N is too big');
110
                        }
111
                    }
112
semval:
113
                    if ($type === null) {
114
                        $type = $symbols[$v]->type;
115
                    }
116
117
                    if ($type === null /* && $ctx->unioned */ && false) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
118
                        throw new ParseException('Type not defined for '.$symbols[$v]->name);
119
                    }
120
121
                    foreach ($this->parseDollar($ctx, $token, $v, $n, $type ? $type->name : null) as $token) {
122
                        yield $token;
123
                    }
124
125
                    continue 2;
126
            }
127
128
            yield $token;
129
        }
130
    }
131
132
    /**
133
     * @param Context     $ctx
134
     * @param Token       $token
135
     * @param int         $nth
136
     * @param int         $len
137
     * @param string|null $type
138
     *
139
     * @return array
140
     */
141
    protected function parseDollar(Context $ctx, Token $token, int $nth, int $len, string $type = null): array
142
    {
143
        if ($token->getValue() === '$') {
144 View Code Duplication
            if ($type) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $type 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...
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...
145
                $mp = $ctx->macros[self::SEMVAL_LHS_TYPED];
146
            } else {
147
                $mp = $ctx->macros[self::SEMVAL_LHS_UNTYPED];
148
            }
149 View Code Duplication
        } else {
0 ignored issues
show
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...
150
            if ($type) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $type 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...
151
                $mp = $ctx->macros[self::SEMVAL_RHS_TYPED];
152
            } else {
153
                $mp = $ctx->macros[self::SEMVAL_RHS_UNTYPED];
154
            }
155
        }
156
157
        $result = '';
158
        for ($i = 0; $i < \mb_strlen($mp); $i++) {
159
            if ($mp[$i] === '%') {
160
                $i++;
161
                switch ($mp[$i]) {
162
                    case 'n':
163
                        $result .= \sprintf('%d', $nth);
164
                        break;
165
                    case 'l':
166
                        $result .= \sprintf('%d', $len);
167
                        break;
168
                    case 't':
169
                        $result .= $type;
170
                        break;
171
                    default:
172
                        $result .= $mp[$i];
173
                }
174
            } else {
175
                $result .= $mp[$i];
176
            }
177
        }
178
179
        return $this->parse($result, $token->getLine(), $token->getFilename());
180
    }
181
}
182