Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a way to avoid throwing Exceptions #324

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{% set key="expression" %}

{{ key|trans|desc("Foo Bar")|meaning("Some Meaning")}}

{{ "text.foo_bar"|trans({}, key) }}

{% trans with {'%name%': 'Johannes'} from key %}text.name{% endtrans %}
59 changes: 47 additions & 12 deletions Tests/Translation/Extractor/File/TwigFileExtractorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

namespace JMS\TranslationBundle\Tests\Translation\Extractor\File;

use Prophecy\Argument;
use Symfony\Bridge\Twig\Form\TwigRendererEngine;
use Symfony\Bridge\Twig\Form\TwigRenderer;
use Symfony\Component\Routing\RequestContext;
Expand All @@ -35,12 +36,20 @@
use JMS\TranslationBundle\Model\MessageCatalogue;
use JMS\TranslationBundle\Twig\TranslationExtension;
use JMS\TranslationBundle\Translation\Extractor\File\TwigFileExtractor;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Bridge\Twig\Extension\FormExtension;

class TwigFileExtractorTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \Twig_Environment
*/
private $env;

protected function setUp()
{
$this->env = $this->createTwigEnvironment();
}

public function testExtractSimpleTemplate()
{
$expected = new MessageCatalogue();
Expand Down Expand Up @@ -136,12 +145,47 @@ public function testEmbeddedTemplate()
$this->assertEquals($expected, $this->extract('embedded_template.html.twig'));
}

public function testSimpleTemplateWithExpressions()
{
$logger = $this->prophesize('Psr\Log\LoggerInterface');
$logger->error(Argument::any(), Argument::any())
->shouldBeCalledTimes(3);

$extractor = new TwigFileExtractor($this->env);
$extractor->setLogger($logger->reveal());

$this->extract('simple_template_with_expressions.html.twig', $extractor);
}

public function testSimpleTemplateWithExpressionsWithoutLogger()
{
$this->setExpectedException('JMS\TranslationBundle\Exception\RuntimeException');
$this->extract('simple_template_with_expressions.html.twig');
}

private function extract($file, TwigFileExtractor $extractor = null)
{
if (!is_file($file = __DIR__.'/Fixture/'.$file)) {
throw new RuntimeException(sprintf('The file "%s" does not exist.', $file));
}

if (null === $extractor) {
$extractor = new TwigFileExtractor($this->env);
}

$ast = $this->env->parse($this->env->tokenize(file_get_contents($file), $file));

$catalogue = new MessageCatalogue();
$extractor->visitTwigFile(new \SplFileInfo($file), $catalogue, $ast);

return $catalogue;
}

/**
* @return \Twig_Environment
*/
private function createTwigEnvironment()
{
$env = new \Twig_Environment();
$env->addExtension(new SymfonyTranslationExtension($translator = new IdentityTranslator(new MessageSelector())));
$env->addExtension(new TranslationExtension($translator, true));
Expand All @@ -157,15 +201,6 @@ private function extract($file, TwigFileExtractor $extractor = null)
}
}

if (null === $extractor) {
$extractor = new TwigFileExtractor($env);
}

$ast = $env->parse($env->tokenize(file_get_contents($file), $file));

$catalogue = new MessageCatalogue();
$extractor->visitTwigFile(new \SplFileInfo($file), $catalogue, $ast);

return $catalogue;
return $env;
}
}
66 changes: 55 additions & 11 deletions Translation/Extractor/File/TwigFileExtractor.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,15 @@
namespace JMS\TranslationBundle\Translation\Extractor\File;

use JMS\TranslationBundle\Exception\RuntimeException;
use Symfony\Bridge\Twig\Node\TransNode;
use JMS\TranslationBundle\Logger\LoggerAwareInterface;
use JMS\TranslationBundle\Model\FileSource;
use JMS\TranslationBundle\Model\Message;
use JMS\TranslationBundle\Model\MessageCatalogue;
use JMS\TranslationBundle\Translation\Extractor\FileVisitorInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bridge\Twig\Node\TransNode;

class TwigFileExtractor implements FileVisitorInterface, \Twig_NodeVisitorInterface
class TwigFileExtractor implements FileVisitorInterface, \Twig_NodeVisitorInterface, LoggerAwareInterface
{
/**
* @var \SplFileInfo
Expand All @@ -43,14 +45,15 @@ class TwigFileExtractor implements FileVisitorInterface, \Twig_NodeVisitorInterf
private $traverser;

/**
* @var array
* @var \Twig_Node[]
*/
private $stack = array();

/**
* TwigFileExtractor constructor.
* @param \Twig_Environment $env
* @var LoggerInterface
*/
private $logger;

public function __construct(\Twig_Environment $env)
{
$this->traverser = new \Twig_NodeTraverser($env, array($this));
Expand All @@ -69,6 +72,9 @@ public function enterNode(\Twig_NodeInterface $node, \Twig_Environment $env)
$id = $node->getNode('body')->getAttribute('data');
$domain = 'messages';
if (null !== $domainNode = $node->getNode('domain')) {
if (!$this->checkNodeIsConstant($domainNode)) {
return $node;
}
$domain = $domainNode->getAttribute('value');
}

Expand All @@ -80,10 +86,9 @@ public function enterNode(\Twig_NodeInterface $node, \Twig_Environment $env)

if ('trans' === $name || 'transchoice' === $name) {
$idNode = $node->getNode('node');
if (!$idNode instanceof \Twig_Node_Expression_Constant) {
if (!$this->checkNodeIsConstant($idNode)) {
return $node;
// FIXME: see below
// throw new \RuntimeException(sprintf('Cannot infer translation id from node "%s". Please refactor to only translate constants.', get_class($idNode)));
}
$id = $idNode->getAttribute('value');

Expand All @@ -92,7 +97,7 @@ public function enterNode(\Twig_NodeInterface $node, \Twig_Environment $env)
$arguments = $node->getNode('arguments');
if ($arguments->hasNode($index)) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You cant remove this comment if you do not comply with the FIXME. It states that a user should be able to "turn this off on a case-by-case basis, similar to @Ignore in PHP".

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I understand your point. But I currently do not see how to properly fix this.

Should I leave the comment?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Im not too sure either.

I am generally not a fan of silencing exceptions. Can @gnat42 or @GOUAILLE give some thoughts on this PR?

$argument = $arguments->getNode($index);
if (!$argument instanceof \Twig_Node_Expression_Constant) {
if (!$this->checkNodeIsConstant($argument)) {
return $node;
// FIXME: Throw exception if there is some way for the user to turn this off
// on a case-by-case basis, similar to @Ignore in PHP
Expand All @@ -105,13 +110,15 @@ public function enterNode(\Twig_NodeInterface $node, \Twig_Environment $env)
$message->addSource(new FileSource((string) $this->file, $node->getLine()));

for ($i=count($this->stack)-2; $i>=0; $i-=1) {
if (!$this->stack[$i] instanceof \Twig_Node_Expression_Filter) {
$currentNode = $this->stack[$i];

if (!$currentNode instanceof \Twig_Node_Expression_Filter) {
break;
}

$name = $this->stack[$i]->getNode('filter')->getAttribute('value');
$name = $currentNode->getNode('filter')->getAttribute('value');
if ('desc' === $name || 'meaning' === $name) {
$arguments = $this->stack[$i]->getNode('arguments');
$arguments = $currentNode->getNode('arguments');
if (!$arguments->hasNode(0)) {
throw new RuntimeException(sprintf('The "%s" filter requires exactly one argument, the description text.', $name));
}
Expand Down Expand Up @@ -202,4 +209,41 @@ public function visitFile(\SplFileInfo $file, MessageCatalogue $catalogue)
public function visitPhpFile(\SplFileInfo $file, MessageCatalogue $catalogue, array $ast)
{
}

/**
* Inject a Logger
*
* @param LoggerInterface $logger
*/
public function setLogger(LoggerInterface $logger)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add PHP doc block

{
$this->logger = $logger;
}

/**
* @param \Twig_Node $node
* @return bool
* @throws RuntimeException
*/
private function checkNodeIsConstant(\Twig_Node $node)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Improve PHP doc block with @throws

{
if ($node instanceof \Twig_Node_Expression_Constant) {
return true;
}

$message = sprintf(
'Cannot infer translation id from node "%s". Please refactor to only translate constants in file "%s" on line %d',
get_class($node),
$this->file,
$node->getLine()
);

if (!$this->logger) {
throw new RuntimeException($message);
}

$this->logger->error($message);

return false;
}
}
13 changes: 13 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,17 @@
<group>performance</group>
</exclude>
</groups>

<filter>
<whitelist processUncoveredFilesFromWhitelist="false">
<directory suffix=".php">*</directory>
<exclude>
<directory>build</directory>
<directory>Resources</directory>
<directory>Tests</directory>
<directory>vendor</directory>
</exclude>
</whitelist>
</filter>

</phpunit>