Completed
Push — travis_php71 ( 735d1d...231818 )
by André
13:40
created

TranslatableExceptionsFileVisitor::enterNode()   C

Complexity

Conditions 13
Paths 14

Size

Total Lines 58
Code Lines 36

Duplication

Lines 28
Ratio 48.28 %

Importance

Changes 0
Metric Value
cc 13
eloc 36
nc 14
nop 1
dl 28
loc 58
rs 6.5104
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
     */
104
    public function enterNode(Node $node)
105
    {
106
        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...
107
            || !$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...
108
            $this->previousNode = $node;
109
110
            return;
111
        }
112
113
        $exceptionClass = $node->expr->class->parts[0];
114
        if (!in_array(strtolower($exceptionClass), array_map('strtolower', $this->exceptionsToExtractFrom))) {
115
            $this->previousNode = $node;
116
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
148
                return;
149
            }
150
151
            throw new RuntimeException($message);
152
        }
153
154
        $id = $node->args[0]->value->value;
155
156
        $message = new Message($id, $this->defaultDomain);
157
        $message->setDesc($desc);
158
        $message->setMeaning($meaning);
159
        $message->addSource($this->fileSourceFactory->create($this->file, $node->getLine()));
160
        $this->catalogue->add($message);
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
     */
178
    public function beforeTraverse(array $nodes)
179
    {
180
    }
181
182
    /**
183
     * @param Node $node
184
     */
185
    public function leaveNode(Node $node)
186
    {
187
    }
188
189
    /**
190
     * @param array $nodes
191
     */
192
    public function afterTraverse(array $nodes)
193
    {
194
    }
195
196
    /**
197
     * @param \SplFileInfo $file
198
     * @param MessageCatalogue $catalogue
199
     */
200
    public function visitFile(\SplFileInfo $file, MessageCatalogue $catalogue)
201
    {
202
    }
203
204
    /**
205
     * @param \SplFileInfo $file
206
     * @param MessageCatalogue $catalogue
207
     * @param \Twig_Node $ast
208
     */
209
    public function visitTwigFile(\SplFileInfo $file, MessageCatalogue $catalogue, \Twig_Node $ast)
210
    {
211
    }
212
213
    /**
214
     * @param Node $node
215
     * @return null|string
216
     */
217 View Code Duplication
    private function getDocCommentForNode(Node $node)
218
    {
219
        // check if there is a doc comment for the ID argument
220
        // ->trans(/** @Desc("FOO") */ 'my.id')
221
        if (null !== $comment = $node->args[0]->getDocComment()) {
222
            return $comment->getText();
223
        }
224
225
        // this may be placed somewhere up in the hierarchy,
226
        // -> /** @Desc("FOO") */ trans('my.id')
227
        // /** @Desc("FOO") */ ->trans('my.id')
228
        // /** @Desc("FOO") */ $translator->trans('my.id')
229
        if (null !== $comment = $node->getDocComment()) {
230
            return $comment->getText();
231
        } elseif (null !== $this->previousNode && $this->previousNode->getDocComment() !== null) {
232
            $comment = $this->previousNode->getDocComment();
233
234
            return is_object($comment) ? $comment->getText() : $comment;
235
        }
236
237
        return null;
238
    }
239
}
240