DollarExpansion   A
last analyzed

Complexity

Total Complexity 35

Size/Duplication

Total Lines 168
Duplicated Lines 7.14 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 35
lcom 1
cbo 4
dl 12
loc 168
rs 9.6
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
D apply() 0 98 26
B parseDollar() 12 40 9

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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::T_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(
75
                            $v === 0 ? Token::T_DOLLAR : 0,
76
                            $token->getValue(),
77
                            $token->getLine(),
78
                            $token->getFilename()
79
                        );
80
                        goto semval;
81
                    }
82
83
                    break;
84
85
                case Token::T_DOLLAR:
86
                    $type = null;
87
                    $token = self::next($tokens);
88
                    if ($token->getValue()[0] === '<') {
89
                        $token = self::next($tokens);
90
                        if ($token->getType() !== Token::T_NAME) {
91
                            throw ParseException::unexpected($token, Token::T_NAME);
92
                        }
93
                        $type = $ctx->intern($token->getValue());
94
                        $dump = self::next($tokens);
95
                        if ($dump->getValue()[0] !== '>') {
96
                            throw ParseException::unexpected($dump, '>');
97
                        }
98
                        $token = self::next($tokens);
99
                    }
100
101
                    if ($token->getType() === Token::T_DOLLAR) {
102
                        $v = 0;
103
                    } elseif ($token->getValue()[0] === '-') {
104
                        $token = self::next($tokens);
105
                        if ($token->getType() !== Token::T_NUMBER) {
106
                            throw ParseException::unexpected($token, Token::T_NUMBER);
107
                        }
108
                        $v = -1 * ((int) $token->getValue());
109
                    } else {
110
                        if ($token->getType() !== Token::T_NUMBER) {
111
                            throw new \RuntimeException('Number expected');
112
                        }
113
                        $v = (int) $token->getValue();
114
                        if ($v > $n) {
115
                            throw new \RuntimeException('N is too big');
116
                        }
117
                    }
118
semval:
119
                    if ($type === null) {
120
                        $type = $symbols[$v]->type;
121
                    }
122
123
                    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...
124
                        throw new ParseException('Type not defined for '.$symbols[$v]->name);
125
                    }
126
127
                    foreach ($this->parseDollar($ctx, $token, $v, $n, $type ? $type->name : null) as $token) {
128
                        yield $token;
129
                    }
130
131
                    continue 2;
132
            }
133
134
            yield $token;
135
        }
136
    }
137
138
    /**
139
     * @param Context     $ctx
140
     * @param Token       $token
141
     * @param int         $nth
142
     * @param int         $len
143
     * @param string|null $type
144
     *
145
     * @return array
146
     */
147
    protected function parseDollar(Context $ctx, Token $token, int $nth, int $len, string $type = null): array
148
    {
149
        if ($token->getValue() === '$') {
150 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...
151
                $mp = $ctx->macros[self::SEMVAL_LHS_TYPED];
152
            } else {
153
                $mp = $ctx->macros[self::SEMVAL_LHS_UNTYPED];
154
            }
155 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...
156
            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...
157
                $mp = $ctx->macros[self::SEMVAL_RHS_TYPED];
158
            } else {
159
                $mp = $ctx->macros[self::SEMVAL_RHS_UNTYPED];
160
            }
161
        }
162
163
        $result = '';
164
        for ($i = 0; $i < \mb_strlen($mp); $i++) {
165
            if ($mp[$i] === '%') {
166
                $i++;
167
                switch ($mp[$i]) {
168
                    case 'n':
169
                        $result .= \sprintf('%d', $nth);
170
                        break;
171
                    case 'l':
172
                        $result .= \sprintf('%d', $len);
173
                        break;
174
                    case 't':
175
                        $result .= $type;
176
                        break;
177
                    default:
178
                        $result .= $mp[$i];
179
                }
180
            } else {
181
                $result .= $mp[$i];
182
            }
183
        }
184
185
        return $this->parse($result, $token->getLine(), $token->getFilename());
186
    }
187
}
188