Skip to content

Commit d666040

Browse files
author
Bartosz Błyszcz
committed
Symfony custom extractor
1 parent 8440a94 commit d666040

File tree

1 file changed

+106
-0
lines changed

1 file changed

+106
-0
lines changed

symfony/extracting-translations.rst

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,109 @@ For example, with `FOSUserBundle<https://github.com/FriendsOfSymfony/FOSUserBund
3636
configs:
3737
app:
3838
external_translations_dir: ["%kernel.root_dir%/vendor/friendsofsymfony/user-bundle/Resources/translations"]
39+
40+
41+
Create custom extractor
42+
-----------------------
43+
44+
Example method whose argument we want to translate
45+
46+
.. code-block:: php
47+
48+
$this->logger->addMessage("text");
49+
50+
51+
Example extractor class that we use to create translations
52+
53+
.. code-block:: php
54+
55+
<?php
56+
57+
namespace App\Extractor;
58+
59+
use PhpParser\Node;
60+
use PhpParser\NodeVisitor;
61+
use Translation\Extractor\Visitor\Php\BasePHPVisitor;
62+
63+
final class MyCustomExtractor extends BasePHPVisitor implements NodeVisitor
64+
{
65+
66+
/**
67+
* {@inheritdoc}
68+
*/
69+
public function beforeTraverse(array $nodes): ?Node
70+
{
71+
return null;
72+
}
73+
74+
/**
75+
* {@inheritdoc}
76+
*/
77+
public function enterNode(Node $node): ?Node
78+
{
79+
if (!$node instanceof Node\Expr\MethodCall) {
80+
return null;
81+
}
82+
83+
if (!is_string($node->name) && !$node->name instanceof Node\Identifier) {
84+
return null;
85+
}
86+
87+
$name = (string) $node->name;
88+
89+
//This "if" check that we have method which interests us
90+
if ($name !== "addMessage") {
91+
return null;
92+
}
93+
94+
$caller = $node->var;
95+
$callerName = isset($caller->name) ? (string) $caller->name : '';
96+
97+
//This "if" check that we have xxx->logger->addMessage()
98+
if ($name === 'addMessage' && $callerName === 'logger' && $caller instanceof Node\Expr\MethodCall) {
99+
100+
//This "if" chack that we have first argument in method as plain text ( not as variable )
101+
//xxx->logger->addMessage("custom-text") is acceptable
102+
if (null !== $label = $this->getStringArgument($node, 0)) {
103+
$this->addLocation($label, $node->getAttribute('startLine'), $node);
104+
}
105+
}
106+
107+
return null;
108+
}
109+
110+
111+
/**
112+
* {@inheritdoc}
113+
*/
114+
public function leaveNode(Node $node): ?Node
115+
{
116+
return null;
117+
}
118+
119+
/**
120+
* {@inheritdoc}
121+
*/
122+
public function afterTraverse(array $nodes): ?Node
123+
{
124+
return null;
125+
}
126+
127+
}
128+
129+
130+
131+
Necessary configuration for proper operation
132+
133+
.. code-block:: yaml
134+
135+
# -- config/service.yml --
136+
137+
# ....
138+
139+
App\Extractor\MyCustomExtractor:
140+
tags:
141+
- { name: php_translation.visitor, type: php }
142+
143+
# ....
144+

0 commit comments

Comments
 (0)