Completed
Push — ezp26704-jms_translation_bundl... ( 8097b0...a61ca5 )
by
unknown
21:52
created

TranslatableExceptionsFileVisitor::visitTwigFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 3
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
4
 * @license For full copyright and license information view LICENSE file distributed with this source code.
5
 */
6
namespace eZ\Publish\Core\MVC\Symfony\Translation;
7
8
use JMS\TranslationBundle\Exception\RuntimeException;
9
use Doctrine\Common\Annotations\DocParser;
10
use JMS\TranslationBundle\Model\Message;
11
use JMS\TranslationBundle\Annotation\Meaning;
12
use JMS\TranslationBundle\Annotation\Desc;
13
use JMS\TranslationBundle\Annotation\Ignore;
14
use JMS\TranslationBundle\Translation\Extractor\FileVisitorInterface;
15
use JMS\TranslationBundle\Model\MessageCatalogue;
16
use JMS\TranslationBundle\Logger\LoggerAwareInterface;
17
use JMS\TranslationBundle\Translation\FileSourceFactory;
18
use PhpParser\Comment\Doc;
19
use PhpParser\Node;
20
use PhpParser\NodeTraverser;
21
use PhpParser\NodeVisitor;
22
use PhpParser\Node\Scalar\String_;
23
use Psr\Log\LoggerInterface;
24
25
/**
26
 * Visits calls to some known translatable exceptions, into the repository_exceptions domain.
27
 */
28
class TranslatableExceptionsFileVisitor implements LoggerAwareInterface, FileVisitorInterface, NodeVisitor
29
{
30
    /**
31
     * @var FileSourceFactory
32
     */
33
    private $fileSourceFactory;
34
35
    /**
36
     * @var NodeTraverser
37
     */
38
    private $traverser;
39
40
    /**
41
     * @var MessageCatalogue
42
     */
43
    private $catalogue;
44
45
    /**
46
     * @var \SplFileInfo
47
     */
48
    private $file;
49
50
    /**
51
     * @var DocParser
52
     */
53
    private $docParser;
54
55
    /**
56
     * @var LoggerInterface
57
     */
58
    private $logger;
59
60
    /**
61
     * @var Node
62
     */
63
    private $previousNode;
64
65
    /**
66
     * @var string
67
     */
68
    protected $defaultDomain = 'repository_exceptions';
69
70
    /**
71
     * Methods and "domain" parameter offset to extract from PHP code
72
     *
73
     * @var array method => position of the "domain" parameter
74
     */
75
    protected $exceptionsToExtractFrom = array(
76
        'contentvalidationexception',
77
        'forbiddenexception'
78
    );
79
80
    /**
81
     * DefaultPhpFileExtractor constructor.
82
     * @param DocParser $docParser
83
     * @param FileSourceFactory $fileSourceFactory
84
     */
85 View Code Duplication
    public function __construct(DocParser $docParser, FileSourceFactory $fileSourceFactory)
86
    {
87
        $this->docParser = $docParser;
88
        $this->fileSourceFactory = $fileSourceFactory;
89
        $this->traverser = new NodeTraverser();
90
        $this->traverser->addVisitor($this);
91
    }
92
93
    /**
94
     * @param LoggerInterface $logger
95
     */
96
    public function setLogger(LoggerInterface $logger)
97
    {
98
        $this->logger = $logger;
99
    }
100
101
    /**
102
     * @param Node $node
103
     * @return void
104
     */
105
    public function enterNode(Node $node)
106
    {
107
        if (!$node instanceof Node\Stmt\Throw_
0 ignored issues
show
Bug introduced by
The class PhpParser\Node\Stmt\Throw_ does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
108
            || !$node->expr instanceof Node\Expr\New_) {
0 ignored issues
show
Bug introduced by
The class PhpParser\Node\Expr\New_ does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
109
            $this->previousNode = $node;
110
111
            return;
112
        }
113
114
        $exceptionClass = $node->expr->class->parts[0];
115
        if (!in_array(strtolower($exceptionClass), array_map('strtolower', $this->exceptionsToExtractFrom))) {
116
            $this->previousNode = $node;
117
            return;
118
        }
119
120
        $node = $node->expr;
121
        $ignore = false;
122
        $desc = $meaning = null;
123 View Code Duplication
        if (null !== $docComment = $this->getDocCommentForNode($node)) {
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...
124
            if ($docComment instanceof Doc) {
0 ignored issues
show
Bug introduced by
The class PhpParser\Comment\Doc does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
125
                $docComment = $docComment->getText();
126
            }
127
            foreach ($this->docParser->parse($docComment, 'file '.$this->file.' near line '.$node->getLine()) as $annot) {
128
                if ($annot instanceof Ignore) {
0 ignored issues
show
Bug introduced by
The class JMS\TranslationBundle\Annotation\Ignore does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
129
                    $ignore = true;
130
                } elseif ($annot instanceof Desc) {
0 ignored issues
show
Bug introduced by
The class JMS\TranslationBundle\Annotation\Desc does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
131
                    $desc = $annot->text;
132
                } elseif ($annot instanceof Meaning) {
0 ignored issues
show
Bug introduced by
The class JMS\TranslationBundle\Annotation\Meaning does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
133
                    $meaning = $annot->text;
134
                }
135
            }
136
        }
137
138 View Code Duplication
        if (!$node->args[0]->value instanceof String_) {
0 ignored issues
show
Bug introduced by
The class PhpParser\Node\Scalar\String_ does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

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...
139
            if ($ignore) {
140
                return;
141
            }
142
143
            $message = sprintf('Can only extract the translation id from a scalar string, but got "%s". Please refactor your code to make it extractable, or add the doc comment /** @Ignore */ to this code element (in %s on line %d).', get_class($node->args[0]->value), $this->file, $node->args[0]->value->getLine());
144
145
            if ($this->logger) {
146
                $this->logger->error($message);
147
                return;
148
            }
149
150
            throw new RuntimeException($message);
151
        }
152
153
        $id = $node->args[0]->value->value;
154
155
        $message = new Message($id, $this->defaultDomain);
156
        $message->setDesc($desc);
157
        $message->setMeaning($meaning);
158
        $message->addSource($this->fileSourceFactory->create($this->file, $node->getLine()));
159
        $this->catalogue->add($message);
160
    }
161
162
    /**
163
     * @param \SplFileInfo $file
164
     * @param MessageCatalogue $catalogue
165
     * @param array $ast
166
     */
167
    public function visitPhpFile(\SplFileInfo $file, MessageCatalogue $catalogue, array $ast)
168
    {
169
        $this->file = $file;
170
        $this->catalogue = $catalogue;
171
        $this->traverser->traverse($ast);
172
    }
173
174
    /**
175
     * @param array $nodes
176
     * @return void
177
     */
178
    public function beforeTraverse(array $nodes)
179
    {
180
    }
181
182
    /**
183
     * @param Node $node
184
     * @return void
185
     */
186
    public function leaveNode(Node $node)
187
    {
188
    }
189
190
    /**
191
     * @param array $nodes
192
     * @return void
193
     */
194
    public function afterTraverse(array $nodes)
195
    {
196
    }
197
198
    /**
199
     * @param \SplFileInfo $file
200
     * @param MessageCatalogue $catalogue
201
     */
202
    public function visitFile(\SplFileInfo $file, MessageCatalogue $catalogue)
203
    {
204
    }
205
206
    /**
207
     * @param \SplFileInfo $file
208
     * @param MessageCatalogue $catalogue
209
     * @param \Twig_Node $ast
210
     */
211
    public function visitTwigFile(\SplFileInfo $file, MessageCatalogue $catalogue, \Twig_Node $ast)
212
    {
213
    }
214
215
    /**
216
     * @param Node $node
217
     * @return null|string
218
     */
219 View Code Duplication
    private function getDocCommentForNode(Node $node)
220
    {
221
        // check if there is a doc comment for the ID argument
222
        // ->trans(/** @Desc("FOO") */ 'my.id')
223
        if (null !== $comment = $node->args[0]->getDocComment()) {
224
            return $comment->getText();
225
        }
226
227
        // this may be placed somewhere up in the hierarchy,
228
        // -> /** @Desc("FOO") */ trans('my.id')
229
        // /** @Desc("FOO") */ ->trans('my.id')
230
        // /** @Desc("FOO") */ $translator->trans('my.id')
231
        if (null !== $comment = $node->getDocComment()) {
232
            return $comment->getText();
233
        } elseif (null !== $this->previousNode && $this->previousNode->getDocComment() !== null) {
234
            $comment = $this->previousNode->getDocComment();
235
            return is_object($comment) ? $comment->getText() : $comment;
236
        }
237
238
        return null;
239
    }
240
}
241