Completed
Push — master ( ecebf9...83c0fc )
by Alexander
03:38
created

NodeExpressionResolver   B

Complexity

Total Complexity 52

Size/Duplication

Total Lines 308
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 13

Test Coverage

Coverage 78.2%

Importance

Changes 3
Bugs 1 Features 0
Metric Value
wmc 52
lcom 1
cbo 13
dl 0
loc 308
ccs 104
cts 133
cp 0.782
rs 7.9487
c 3
b 1
f 0

21 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getConstantName() 0 4 1
A getValue() 0 4 1
A isConstant() 0 4 1
A process() 0 7 1
A resolve() 0 17 2
A resolveScalarDNumber() 0 4 1
A resolveScalarLNumber() 0 4 1
A resolveScalarString() 0 4 1
A resolveScalarMagicConstFunction() 0 8 2
A resolveScalarMagicConstMethod() 0 10 2
A resolveScalarMagicConstNamespace() 0 12 3
A resolveScalarMagicConstClass() 0 14 4
A resolveScalarMagicConstDir() 0 8 2
A resolveScalarMagicConstFile() 0 8 2
A resolveScalarMagicConstLine() 0 4 2
C resolveExprConstFetch() 0 34 8
A resolveExprClassConstFetch() 0 12 2
A resolveExprArray() 0 11 3
D fetchReflectionClass() 0 35 9
A resolveScalarMagicConstTrait() 0 8 3

How to fix   Complexity   

Complex Class

Complex classes like NodeExpressionResolver often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use NodeExpressionResolver, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Parser Reflection API
4
 *
5
 * @copyright Copyright 2015, Lisachenko Alexander <[email protected]>
6
 *
7
 * This source file is subject to the license that is bundled
8
 * with this source code in the file LICENSE.
9
 */
10
11
namespace Go\ParserReflection\ValueResolver;
12
13
use Go\ParserReflection\ReflectionClass;
14
use Go\ParserReflection\ReflectionException;
15
use Go\ParserReflection\ReflectionFileNamespace;
16
use PhpParser\Node;
17
use PhpParser\Node\Expr;
18
use PhpParser\Node\Scalar;
19
use PhpParser\Node\Scalar\MagicConst;
20
21
/**
22
 * Tries to resolve expression into value
23
 */
24
class NodeExpressionResolver
25
{
26
27
    /**
28
     * List of exception for constant fetch
29
     *
30
     * @var array
31
     */
32
    private static $notConstants = [
33
        'true'  => true,
34
        'false' => true,
35
        'null'  => true,
36
    ];
37
38
    /**
39
     * Name of the constant (if present)
40
     *
41
     * @var null|string
42
     */
43
    private $constantName = null;
44
45
    /**
46
     * Current reflection context for parsing
47
     *
48
     * @var mixed
49
     */
50
    private $context;
51
52
    /**
53
     * Flag if expression is constant
54
     *
55
     * @var bool
56
     */
57
    private $isConstant = false;
58
59
    /**
60
     * Node resolving level, 1 = top-level
61
     *
62
     * @var int
63
     */
64
    private $nodeLevel = 0;
65
66
    /**
67
     * @var mixed Value of expression/constant
68
     */
69
    private $value;
70
71 15
    public function __construct($context)
72
    {
73 15
        $this->context = $context;
74 15
    }
75
76 8
    public function getConstantName()
77
    {
78 8
        return $this->constantName;
79
    }
80
81 15
    public function getValue()
82
    {
83 15
        return $this->value;
84
    }
85
86 8
    public function isConstant()
87
    {
88 8
        return $this->isConstant;
89
    }
90
91
    /**
92
     * {@inheritDoc}
93
     */
94 15
    public function process(Node $node)
95
    {
96 15
        $this->nodeLevel    = 0;
97 15
        $this->isConstant   = false;
98 15
        $this->constantName = null;
99 15
        $this->value        = $this->resolve($node);
100 15
    }
101
102
    /**
103
     * Resolves node into valid value
104
     *
105
     * @param Node $node
106
     *
107
     * @return mixed
108
     */
109 15
    protected function resolve(Node $node)
110
    {
111 15
        $value = null;
112
        try {
113 15
            ++$this->nodeLevel;
114
115 15
            $nodeType   = $node->getType();
116 15
            $methodName = 'resolve' . str_replace('_', '', $nodeType);
117 15
            if (method_exists($this, $methodName)) {
118 15
                $value = $this->$methodName($node);
119 15
            }
120 15
        } finally {
121 15
            --$this->nodeLevel;
122
        }
123
124 15
        return $value;
125
    }
126
127 2
    protected function resolveScalarDNumber(Scalar\DNumber $node)
128
    {
129 2
        return $node->value;
130
    }
131
132 11
    protected function resolveScalarLNumber(Scalar\LNumber $node)
133
    {
134 11
        return $node->value;
135
    }
136
137 5
    protected function resolveScalarString(Scalar\String_ $node)
138
    {
139 5
        return $node->value;
140
    }
141
142
    protected function resolveScalarMagicConstMethod()
143
    {
144
        if ($this->context instanceof \ReflectionMethod) {
145
            $fullName = $this->context->getDeclaringClass()->getName() . '::' . $this->context->getShortName();
0 ignored issues
show
introduced by
Consider using $this->context->class. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
146
147
            return $fullName;
148
        }
149
150
        return '';
151
    }
152
153
    protected function resolveScalarMagicConstFunction()
154
    {
155
        if ($this->context instanceof \ReflectionFunctionAbstract) {
156
            return $this->context->getName();
157
        }
158
159
        return '';
160
    }
161
162 9
    protected function resolveScalarMagicConstNamespace()
163
    {
164 9
        if (method_exists($this->context, 'getNamespaceName')) {
165 7
            return $this->context->getNamespaceName();
166
        }
167
168 2
        if ($this->context instanceof ReflectionFileNamespace) {
169 2
            return $this->context->getName();
170
        }
171
172
        return '';
173
    }
174
175 7
    protected function resolveScalarMagicConstClass()
176
    {
177 7
        if ($this->context instanceof \ReflectionClass) {
178 1
            return $this->context->getName();
0 ignored issues
show
Bug introduced by
Consider using $this->context->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
179
        }
180 6
        if (method_exists($this->context, 'getDeclaringClass')) {
181
            $declaringClass = $this->context->getDeclaringClass();
182
            if ($declaringClass instanceof \ReflectionClass) {
183
                return $declaringClass->getName();
0 ignored issues
show
Bug introduced by
Consider using $declaringClass->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
184
            }
185
        }
186
187 6
        return '';
188
    }
189
190 1
    protected function resolveScalarMagicConstDir()
191
    {
192 1
        if (method_exists($this->context, 'getFileName')) {
193 1
            return dirname($this->context->getFileName());
194
        }
195
196
        return '';
197
    }
198
199 3
    protected function resolveScalarMagicConstFile()
200
    {
201 3
        if (method_exists($this->context, 'getFileName')) {
202 3
            return $this->context->getFileName();
203
        }
204
205
        return '';
206
    }
207
208 3
    protected function resolveScalarMagicConstLine(MagicConst\Line $node)
209
    {
210 3
        return $node->hasAttribute('startLine') ? $node->getAttribute('startLine') : 0;
211
    }
212
213 1
    protected function resolveScalarMagicConstTrait()
214
    {
215 1
        if ($this->context instanceof \ReflectionClass && $this->context->isTrait()) {
216 1
            return $this->context->getName();
0 ignored issues
show
Bug introduced by
Consider using $this->context->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
217
        }
218
219
        return '';
220
    }
221
222 11
    protected function resolveExprConstFetch(Expr\ConstFetch $node)
223
    {
224 11
        $constantValue = null;
225 11
        $isResolved    = false;
226
227
        /** @var ReflectionFileNamespace|null $fileNamespace */
228 11
        $fileNamespace = null;
0 ignored issues
show
Unused Code introduced by
$fileNamespace 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...
229 11
        $isFQNConstant = $node->name instanceof Node\Name\FullyQualified;
230 11
        $constantName  = $node->name->toString();
231
232 11
        if (!$isFQNConstant) {
233 11
            if (method_exists($this->context, 'getFileName')) {
234 11
                $fileName      = $this->context->getFileName();
235 11
                $namespaceName = $this->context->getNamespaceName();
236 11
                $fileNamespace = new ReflectionFileNamespace($fileName, $namespaceName);
237 11
                if ($fileNamespace->hasConstant($constantName)) {
238 8
                    $constantValue = $fileNamespace->getConstant($constantName);
239 8
                    $constantName  = $fileNamespace->getName() . '\\' . $constantName;
240 8
                    $isResolved    = true;
241 8
                }
242 11
            }
243 11
        }
244
245 11
        if (!$isResolved && defined($constantName)) {
246 10
            $constantValue = constant($constantName);
247 10
        }
248
249 11
        if ($this->nodeLevel === 1 && !isset(self::$notConstants[$constantName])) {
250 8
            $this->isConstant   = true;
251 8
            $this->constantName = $constantName;
252 8
        }
253
254 11
        return $constantValue;
255
    }
256
257 3
    protected function resolveExprClassConstFetch(Expr\ClassConstFetch $node)
258
    {
259 3
        $refClass     = $this->fetchReflectionClass($node->class);
260 3
        $constantName = $node->name;
261
262
        // special handling of ::class constants
263 3
        if ('class' === $constantName) {
264 1
            return $refClass->getName();
265
        }
266
267 3
        return $refClass->getConstant($constantName);
268
    }
269
270 8
    protected function resolveExprArray(Expr\Array_ $node)
271
    {
272 8
        $result = [];
273 8
        foreach ($node->items as $itemIndex => $arrayItem) {
274 7
            $itemValue = $this->resolve($arrayItem->value);
275 7
            $itemKey   = isset($arrayItem->key) ? $this->resolve($arrayItem->key) : $itemIndex;
276 7
            $result[$itemKey] = $itemValue;
277 8
        }
278
279 8
        return $result;
280
    }
281
282
    /**
283
     * Utility method to fetch reflection class instance by name
284
     *
285
     * Supports:
286
     *   'self' keyword
287
     *   'parent' keyword
288
     *    not-FQN class names
289
     *
290
     * @param Node\Name $node Class name node
291
     *
292
     * @return bool|\ReflectionClass
293
     *
294
     * @throws ReflectionException
295
     */
296 3
    private function fetchReflectionClass(Node\Name $node)
297
    {
298 3
        $className  = $node->toString();
299 3
        $isFQNClass = $node instanceof Node\Name\FullyQualified;
300 3
        if ($isFQNClass) {
301 1
            return new ReflectionClass($className);
302
        }
303
304 3
        if ('self' === $className) {
305 3
            if ($this->context instanceof \ReflectionClass) {
306 3
                return $this->context;
307
            } elseif (method_exists($this->context, 'getDeclaringClass')) {
308
                return $this->context->getDeclaringClass();
309
            }
310
        }
311
312 1
        if ('parent' === $className) {
313 1
            if ($this->context instanceof \ReflectionClass) {
314 1
                return $this->context->getParentClass();
315
            } elseif (method_exists($this->context, 'getDeclaringClass')) {
316
                return $this->context->getDeclaringClass()->getParentClass();
317
            }
318
        }
319
320
        if (method_exists($this->context, 'getFileName')) {
321
            /** @var ReflectionFileNamespace|null $fileNamespace */
322
            $fileName      = $this->context->getFileName();
323
            $namespaceName = $this->context->getNamespaceName();
324
325
            $fileNamespace = new ReflectionFileNamespace($fileName, $namespaceName);
326
            return $fileNamespace->getClass($className);
327
        }
328
329
        throw new ReflectionException("Can not resolve class $className");
330
    }
331
}
332