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

ValidationErrorFileVisitor::getDocCommentForNode()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 21
Code Lines 9

Duplication

Lines 21
Ratio 100 %

Importance

Changes 0
Metric Value
cc 6
eloc 9
nc 5
nop 1
dl 21
loc 21
rs 8.7624
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 ValidationErrorFileVisitor 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 $classToExtractFrom = 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\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...
108
            || !is_string($node->class)
109
            || strtolower($node->class) !== 'validationerror' ) {
110
            $this->previousNode = $node;
111
112
            return;
113
        }
114
115
        $ignore = false;
116
        $desc = $meaning = null;
117 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...
118
            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...
119
                $docComment = $docComment->getText();
120
            }
121
            foreach ($this->docParser->parse($docComment, 'file '.$this->file.' near line '.$node->getLine()) as $annot) {
122
                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...
123
                    $ignore = true;
124
                } 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...
125
                    $desc = $annot->text;
126
                } 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...
127
                    $meaning = $annot->text;
128
                }
129
            }
130
        }
131
132 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...
133
            if ($ignore) {
134
                return;
135
            }
136
137
            $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());
138
139
            if ($this->logger) {
140
                $this->logger->error($message);
141
                return;
142
            }
143
144
            throw new RuntimeException($message);
145
        }
146
147
        $message = new Message($node->args[0]->value->value, $this->defaultDomain);
148
        $message->setDesc($desc);
149
        $message->setMeaning($meaning);
150
        $message->addSource($this->fileSourceFactory->create($this->file, $node->getLine()));
151
        $this->catalogue->add($message);
152
153
        // plural
154
        if ($node->args[1]->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...
155
            $message = new Message($node->args[1]->value->value, $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
    /**
164
     * @param \SplFileInfo $file
165
     * @param MessageCatalogue $catalogue
166
     * @param array $ast
167
     */
168
    public function visitPhpFile(\SplFileInfo $file, MessageCatalogue $catalogue, array $ast)
169
    {
170
        $this->file = $file;
171
        $this->catalogue = $catalogue;
172
        $this->traverser->traverse($ast);
173
    }
174
175
    /**
176
     * @param array $nodes
177
     * @return void
178
     */
179
    public function beforeTraverse(array $nodes)
180
    {
181
    }
182
183
    /**
184
     * @param Node $node
185
     * @return void
186
     */
187
    public function leaveNode(Node $node)
188
    {
189
    }
190
191
    /**
192
     * @param array $nodes
193
     * @return void
194
     */
195
    public function afterTraverse(array $nodes)
196
    {
197
    }
198
199
    /**
200
     * @param \SplFileInfo $file
201
     * @param MessageCatalogue $catalogue
202
     */
203
    public function visitFile(\SplFileInfo $file, MessageCatalogue $catalogue)
204
    {
205
    }
206
207
    /**
208
     * @param \SplFileInfo $file
209
     * @param MessageCatalogue $catalogue
210
     * @param \Twig_Node $ast
211
     */
212
    public function visitTwigFile(\SplFileInfo $file, MessageCatalogue $catalogue, \Twig_Node $ast)
213
    {
214
    }
215
216
    /**
217
     * @param Node $node
218
     * @return null|string
219
     */
220 View Code Duplication
    private function getDocCommentForNode(Node $node)
221
    {
222
        // check if there is a doc comment for the ID argument
223
        // ->trans(/** @Desc("FOO") */ 'my.id')
224
        if (null !== $comment = $node->args[0]->getDocComment()) {
225
            return $comment->getText();
226
        }
227
228
        // this may be placed somewhere up in the hierarchy,
229
        // -> /** @Desc("FOO") */ trans('my.id')
230
        // /** @Desc("FOO") */ ->trans('my.id')
231
        // /** @Desc("FOO") */ $translator->trans('my.id')
232
        if (null !== $comment = $node->getDocComment()) {
233
            return $comment->getText();
234
        } elseif (null !== $this->previousNode && $this->previousNode->getDocComment() !== null) {
235
            $comment = $this->previousNode->getDocComment();
236
            return is_object($comment) ? $comment->getText() : $comment;
237
        }
238
239
        return null;
240
    }
241
}
242