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