Completed
Push — master ( 173f42...a86a81 )
by Marco
17s queued 10s
created

resolveClassNameForClassNameConstant()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 2
cts 4
cp 0.5
rs 9.7666
c 0
b 0
f 0
cc 4
nc 3
nop 2
crap 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Roave\BetterReflection\NodeCompiler;
6
7
use PhpParser\ConstExprEvaluator;
8
use PhpParser\Node;
9
use Roave\BetterReflection\Reflection\ReflectionClass;
10
use Roave\BetterReflection\Reflection\ReflectionClassConstant;
11
use Roave\BetterReflection\Reflector\Exception\IdentifierNotFound;
12
use Roave\BetterReflection\Util\FileHelper;
13
use function constant;
14
use function defined;
15
use function dirname;
16
use function realpath;
17
use function reset;
18
19
class CompileNodeToValue
20
{
21
    /**
22
     * Compile an expression from a node into a value.
23
     *
24
     * @param Node\Stmt\Expression|Node\Expr $node Node has to be processed by the PhpParser\NodeVisitor\NameResolver
25
     *
26
     * @return mixed
27
     *
28
     * @throws Exception\UnableToCompileNode
29
     */
30 111
    public function __invoke(Node $node, CompilerContext $context)
31
    {
32 111
        if ($node instanceof Node\Stmt\Expression) {
33 94
            return $this($node->expr, $context);
34
        }
35
36
        $constExprEvaluator = new ConstExprEvaluator(function (Node\Expr $node) use ($context) {
37 18
            if ($node instanceof Node\Expr\ConstFetch) {
38 4
                return $this->compileConstFetch($node, $context);
39
            }
40
41 14
            if ($node instanceof Node\Expr\ClassConstFetch) {
42 13
                return $this->compileClassConstFetch($node, $context);
43
            }
44
45 1
            if ($node instanceof Node\Scalar\MagicConst\Dir) {
46
                return $this->compileDirConstant($context);
47
            }
48
49 1
            if ($node instanceof Node\Scalar\MagicConst\Class_) {
50
                return $this->compileClassConstant($context);
51
            }
52
53 1
            throw Exception\UnableToCompileNode::forUnRecognizedExpressionInContext($node, $context);
54 111
        });
55
56 111
        return $constExprEvaluator->evaluateDirectly($node);
0 ignored issues
show
Compatibility introduced by Jaroslav Hanslík
$node of type object<PhpParser\Node> is not a sub-type of object<PhpParser\Node\Expr>. It seems like you assume a concrete implementation of the interface PhpParser\Node to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
57
    }
58
59
    /**
60
     * Compile constant expressions
61
     *
62
     * @return bool|mixed|null
63
     *
64
     * @throws Exception\UnableToCompileNode
65
     */
66 4
    private function compileConstFetch(Node\Expr\ConstFetch $constNode, CompilerContext $context)
67
    {
68 4
        $firstName = reset($constNode->name->parts);
69 4
        switch ($firstName) {
70 4
            case 'null':
71
                return null;
72 4
            case 'false':
73
                return false;
74 4
            case 'true':
75
                return true;
76
            default:
77 4
                if (! defined($firstName)) {
78 1
                    throw Exception\UnableToCompileNode::becauseOfNotFoundConstantReference($context, $constNode);
79
                }
80
81 3
                return constant($firstName);
82
        }
83
    }
84
85
    /**
86
     * Compile class constants
87
     *
88
     * @return string|int|float|bool|mixed[]|null
89
     *
90
     * @throws IdentifierNotFound
91
     * @throws Exception\UnableToCompileNode If a referenced constant could not be located on the expected referenced class.
92
     */
93 13
    private function compileClassConstFetch(Node\Expr\ClassConstFetch $node, CompilerContext $context)
94
    {
95
        /** @var Node\Identifier $node->name */
96 13
        $nodeName = $node->name->name;
97
        /** @var Node\Name $node->class */
98 13
        $className = $node->class->toString();
99
100 13
        if ($nodeName === 'class') {
101 4
            return $this->resolveClassNameForClassNameConstant($className, $context);
102
        }
103
104
        /** @var ReflectionClass|null $classInfo */
105 9
        $classInfo = null;
106
107 9
        if ($className === 'self' || $className === 'static') {
108 5
            $classInfo = $context->getSelf()->hasConstant($nodeName) ? $context->getSelf() : null;
109
        } elseif ($className === 'parent') {
110
            $classInfo = $context->getSelf()->getParentClass();
111 9
        }
112
113 4
        if ($classInfo === null) {
114
            /** @var ReflectionClass $classInfo */
115
            $classInfo = $context->getReflector()->reflect($className);
116 9
        }
117
118 9
        $reflectionConstant = $classInfo->getReflectionConstant($nodeName);
119 1
120
        if (! $reflectionConstant instanceof ReflectionClassConstant) {
121
            throw Exception\UnableToCompileNode::becauseOfNotFoundClassConstantReference($context, $classInfo, $node);
122 8
        }
123 8
124 8
        return $this->__invoke(
125
            $reflectionConstant->getAst()->consts[$reflectionConstant->getPositionInAst()]->value,
126
            new CompilerContext($context->getReflector(), $classInfo)
127
        );
128
    }
129
130
    /**
131
     * Compile a __DIR__ node
132
     */
133
    private function compileDirConstant(CompilerContext $context) : string
134
    {
135
        return FileHelper::normalizeWindowsPath(dirname(realpath($context->getFileName())));
136
    }
137
138
    /**
139
     * Compiles magic constant __CLASS__
140
     */
141
    private function compileClassConstant(CompilerContext $context) : string
142
    {
143
        return $context->hasSelf() ? $context->getSelf()->getName() : '';
144 5
    }
145
146 5
    private function resolveClassNameForClassNameConstant(string $className, CompilerContext $context) : string
147 5
    {
148
        if ($className === 'self' || $className === 'static') {
149
            return $context->getSelf()->getName();
150
        }
151
152
        if ($className === 'parent') {
153
            /** @var ReflectionClass $parentClass */
154
            $parentClass = $context->getSelf()->getParentClass();
155
156
            return $parentClass->getName();
157
        }
158
159
        return $className;
160
    }
161
}
162