Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
PhpParserNodeVisitorClassName
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
3 / 3
7
100.00% covered (success)
100.00%
1 / 1
 enterNode
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
5
 getClassname
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getNamespaceName
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3/**
4 * @author: Doug Wilbourne (dougwilbourne@gmail.com)
5 * @version 1.0
6 */
7
8namespace pvc\err;
9
10use PhpParser\Node;
11use PhpParser\Node\Stmt\Class_;
12use PhpParser\Node\Stmt\Namespace_;
13use PhpParser\NodeTraverser;
14use PhpParser\NodeVisitorAbstract;
15
16/**
17 * PhpParserNodeVisitorClassName gets the class name from an Abstract Syntax Tree and then stops the traversal.
18 *
19 * The success of the enterNode method setting the className is contingent on
20 * running a NameResolver through the node prior to this visitor.  Need to write a decorator for NameResolver that
21 * has a method to get the namespacedName property of the node......
22 */
23
24class PhpParserNodeVisitorClassName extends NodeVisitorAbstract
25{
26    protected string $className;
27
28    protected string $namespaceName;
29
30    /**
31     * enterNode inspects the current node and if it is an instance of Class_, returns the class string/class name
32     * @param Node $node
33     * @return int|null
34     */
35    public function enterNode(Node $node): ?int
36    {
37        if ($node instanceof Namespace_) {
38            /** phpstan complains if we don't test for null */
39            $this->namespaceName = ($node->name instanceof \PhpParser\Node\Name
40                ? $node->name->toString() : '');
41        }
42
43        if ($node instanceof Class_) {
44            /** phpstan complains if we don't test for null */
45            $this->className = ($node->name instanceof
46            \PhpParser\Node\Identifier ? $node->name->toString() : '');
47
48            /** return value STOP_TRAVERSAL stops the node traverser from going any further */
49            return NodeTraverser::STOP_TRAVERSAL;
50        }
51        /**
52         * returning null will have the traverser keep traversing nodes in the AST.
53         */
54        return null;
55    }
56
57    /**
58     * getClassname
59     * @return string
60     */
61    public function getClassname(): string
62    {
63        return $this->className ?? '';
64    }
65
66    /**
67     * getNamespaceName
68     * @return string
69     */
70    public function getNamespaceName(): string
71    {
72        return $this->namespaceName ?? '';
73    }
74}