Completed
Push — master ( 6c8b2f...a31f38 )
by Tobias
16:10
created

TranslateAnnotationVisitor::enterNode()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 13
cts 13
cp 1
rs 8.8817
c 0
b 0
f 0
cc 6
nc 6
nop 1
crap 6
1
<?php
2
3
/*
4
 * This file is part of the PHP Translation package.
5
 *
6
 * (c) PHP Translation team <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Translation\Extractor\Visitor\Php;
13
14
use Doctrine\Common\Annotations\DocParser;
15
use PhpParser\Comment;
16
use PhpParser\Node;
17
use PhpParser\NodeVisitor;
18
use Translation\Extractor\Annotation\Translate;
19
20
/**
21
 * Class TranslationAnnotationVisitor.
22
 *
23
 * Supports using @Translate annotation for marking string nodes to be added to the dictionary
24
 */
25
class TranslateAnnotationVisitor extends BasePHPVisitor implements NodeVisitor
26
{
27
    /** @var DocParser */
28
    protected $translateDocParser;
29
30
    /**
31
     * @return DocParser
32
     */
33 2
    private function getTranslateDocParser()
34
    {
35 2
        if (null === $this->translateDocParser) {
36 2
            $this->translateDocParser = new DocParser();
37
38 2
            $this->translateDocParser->setImports([
39 2
                'translate' => Translate::class,
40
            ]);
41 2
            $this->translateDocParser->setIgnoreNotImportedAnnotations(true);
42
        }
43
44 2
        return $this->translateDocParser;
45
    }
46
47 2
    public function enterNode(Node $node)
48
    {
49
        // look for strings
50 2
        if (!$node instanceof Node\Scalar\String_) {
51 2
            return null;
52
        }
53
54
        //look for string with comment
55 2
        $comments = $node->getAttribute('comments', []);
56 2
        if (!count($comments)) {
57 2
            return null;
58
        }
59
60 2
        foreach ($comments as $comment) {
61 2
            if (!$comment instanceof Comment\Doc) {
62 2
                return null;
63
            }
64
65 2
            foreach ($this->getTranslateDocParser()->parse($comment->getText()) as $annotation) {
66
                //add phrase to dictionary
67 2
                $this->addLocation($node->value, $node->getAttribute('startLine'), $node, ['domain' => $annotation->getDomain()]);
68
69 2
                break;
70
            }
71
        }
72 2
    }
73
74 2
    public function leaveNode(Node $node)
75
    {
76 2
    }
77
78 2
    public function beforeTraverse(array $nodes)
79
    {
80 2
    }
81
82 2
    public function afterTraverse(array $nodes)
83
    {
84 2
    }
85
}
86