Skip to content

Symfony custom extractor #52

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

Merged
merged 3 commits into from
Aug 11, 2020
Merged
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
103 changes: 103 additions & 0 deletions symfony/extracting-translations.rst
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,106 @@ For example, with `FOSUserBundle<https://github.com/FriendsOfSymfony/FOSUserBund
configs:
app:
external_translations_dir: ["%kernel.root_dir%/vendor/friendsofsymfony/user-bundle/Resources/translations"]


Creating custom extractor
-------------------------

Example of method whose argument we want to translate

.. code-block:: php

$this->logger->addMessage("text");

Example of extractor class that we use to create translations

.. code-block:: php

<?php

namespace App\Extractor;

use PhpParser\Node;
use PhpParser\NodeVisitor;
use Translation\Extractor\Visitor\Php\BasePHPVisitor;

final class MyCustomExtractor extends BasePHPVisitor implements NodeVisitor
{
/**
* {@inheritdoc}
*/
public function beforeTraverse(array $nodes): ?Node
{
return null;
}

/**
* {@inheritdoc}
*/
public function enterNode(Node $node): ?Node
{
if (!$node instanceof Node\Expr\MethodCall) {
return null;
}

if (!is_string($node->name) && !$node->name instanceof Node\Identifier) {
return null;
}

$name = (string) $node->name;

//This "if" check that we have method which interests us
if ($name !== "addMessage") {
return null;
}

$caller = $node->var;
$callerName = isset($caller->name) ? (string) $caller->name : '';

//This "if" check that we have xxx->logger->addMessage()
if ($callerName === 'logger' && $caller instanceof Node\Expr\MethodCall) {

//This "if" chack that we have first argument in method as plain text ( not as variable )
//xxx->logger->addMessage("custom-text") is acceptable
if (null !== $label = $this->getStringArgument($node, 0)) {
$this->addLocation($label, $node->getAttribute('startLine'), $node);
}
}

return null;
}


/**
* {@inheritdoc}
*/
public function leaveNode(Node $node): ?Node
{
return null;
}

/**
* {@inheritdoc}
*/
public function afterTraverse(array $nodes): ?Node
{
return null;
}
}



Necessary configuration for proper operation

.. code-block:: yaml

# -- config/service.yml --

# ....

App\Extractor\MyCustomExtractor:
tags:
- { name: php_translation.visitor, type: php }

# ....