PhpExtractor.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Translation\Extractor;
  11. use Symfony\Component\Finder\Finder;
  12. use Symfony\Component\Translation\MessageCatalogue;
  13. /**
  14. * PhpExtractor extracts translation messages from a PHP template.
  15. *
  16. * @author Michel Salib <michelsalib@hotmail.com>
  17. */
  18. class PhpExtractor extends AbstractFileExtractor implements ExtractorInterface
  19. {
  20. const MESSAGE_TOKEN = 300;
  21. const METHOD_ARGUMENTS_TOKEN = 1000;
  22. const DOMAIN_TOKEN = 1001;
  23. /**
  24. * Prefix for new found message.
  25. *
  26. * @var string
  27. */
  28. private $prefix = '';
  29. /**
  30. * The sequence that captures translation messages.
  31. *
  32. * @var array
  33. */
  34. protected $sequences = [
  35. [
  36. '->',
  37. 'trans',
  38. '(',
  39. self::MESSAGE_TOKEN,
  40. ',',
  41. self::METHOD_ARGUMENTS_TOKEN,
  42. ',',
  43. self::DOMAIN_TOKEN,
  44. ],
  45. [
  46. '->',
  47. 'transChoice',
  48. '(',
  49. self::MESSAGE_TOKEN,
  50. ',',
  51. self::METHOD_ARGUMENTS_TOKEN,
  52. ',',
  53. self::METHOD_ARGUMENTS_TOKEN,
  54. ',',
  55. self::DOMAIN_TOKEN,
  56. ],
  57. [
  58. '->',
  59. 'trans',
  60. '(',
  61. self::MESSAGE_TOKEN,
  62. ],
  63. [
  64. '->',
  65. 'transChoice',
  66. '(',
  67. self::MESSAGE_TOKEN,
  68. ],
  69. ];
  70. /**
  71. * {@inheritdoc}
  72. */
  73. public function extract($resource, MessageCatalogue $catalog)
  74. {
  75. $files = $this->extractFiles($resource);
  76. foreach ($files as $file) {
  77. $this->parseTokens(token_get_all(file_get_contents($file)), $catalog, $file);
  78. gc_mem_caches();
  79. }
  80. }
  81. /**
  82. * {@inheritdoc}
  83. */
  84. public function setPrefix($prefix)
  85. {
  86. $this->prefix = $prefix;
  87. }
  88. /**
  89. * Normalizes a token.
  90. *
  91. * @param mixed $token
  92. *
  93. * @return string
  94. */
  95. protected function normalizeToken($token)
  96. {
  97. if (isset($token[1]) && 'b"' !== $token) {
  98. return $token[1];
  99. }
  100. return $token;
  101. }
  102. /**
  103. * Seeks to a non-whitespace token.
  104. */
  105. private function seekToNextRelevantToken(\Iterator $tokenIterator)
  106. {
  107. for (; $tokenIterator->valid(); $tokenIterator->next()) {
  108. $t = $tokenIterator->current();
  109. if (T_WHITESPACE !== $t[0]) {
  110. break;
  111. }
  112. }
  113. }
  114. private function skipMethodArgument(\Iterator $tokenIterator)
  115. {
  116. $openBraces = 0;
  117. for (; $tokenIterator->valid(); $tokenIterator->next()) {
  118. $t = $tokenIterator->current();
  119. if ('[' === $t[0] || '(' === $t[0]) {
  120. ++$openBraces;
  121. }
  122. if (']' === $t[0] || ')' === $t[0]) {
  123. --$openBraces;
  124. }
  125. if ((0 === $openBraces && ',' === $t[0]) || (-1 === $openBraces && ')' === $t[0])) {
  126. break;
  127. }
  128. }
  129. }
  130. /**
  131. * Extracts the message from the iterator while the tokens
  132. * match allowed message tokens.
  133. */
  134. private function getValue(\Iterator $tokenIterator)
  135. {
  136. $message = '';
  137. $docToken = '';
  138. $docPart = '';
  139. for (; $tokenIterator->valid(); $tokenIterator->next()) {
  140. $t = $tokenIterator->current();
  141. if ('.' === $t) {
  142. // Concatenate with next token
  143. continue;
  144. }
  145. if (!isset($t[1])) {
  146. break;
  147. }
  148. switch ($t[0]) {
  149. case T_START_HEREDOC:
  150. $docToken = $t[1];
  151. break;
  152. case T_ENCAPSED_AND_WHITESPACE:
  153. case T_CONSTANT_ENCAPSED_STRING:
  154. if ('' === $docToken) {
  155. $message .= PhpStringTokenParser::parse($t[1]);
  156. } else {
  157. $docPart = $t[1];
  158. }
  159. break;
  160. case T_END_HEREDOC:
  161. $message .= PhpStringTokenParser::parseDocString($docToken, $docPart);
  162. $docToken = '';
  163. $docPart = '';
  164. break;
  165. case T_WHITESPACE:
  166. break;
  167. default:
  168. break 2;
  169. }
  170. }
  171. return $message;
  172. }
  173. /**
  174. * Extracts trans message from PHP tokens.
  175. *
  176. * @param array $tokens
  177. * @param MessageCatalogue $catalog
  178. * @param string $filename
  179. */
  180. protected function parseTokens($tokens, MessageCatalogue $catalog/*, string $filename*/)
  181. {
  182. if (\func_num_args() < 3 && __CLASS__ !== \get_class($this) && __CLASS__ !== (new \ReflectionMethod($this, __FUNCTION__))->getDeclaringClass()->getName() && !$this instanceof \PHPUnit\Framework\MockObject\MockObject && !$this instanceof \Prophecy\Prophecy\ProphecySubjectInterface) {
  183. @trigger_error(sprintf('The "%s()" method will have a new "string $filename" argument in version 5.0, not defining it is deprecated since Symfony 4.3.', __METHOD__), E_USER_DEPRECATED);
  184. }
  185. $filename = 2 < \func_num_args() ? func_get_arg(2) : '';
  186. $tokenIterator = new \ArrayIterator($tokens);
  187. for ($key = 0; $key < $tokenIterator->count(); ++$key) {
  188. foreach ($this->sequences as $sequence) {
  189. $message = '';
  190. $domain = 'messages';
  191. $tokenIterator->seek($key);
  192. foreach ($sequence as $sequenceKey => $item) {
  193. $this->seekToNextRelevantToken($tokenIterator);
  194. if ($this->normalizeToken($tokenIterator->current()) === $item) {
  195. $tokenIterator->next();
  196. continue;
  197. } elseif (self::MESSAGE_TOKEN === $item) {
  198. $message = $this->getValue($tokenIterator);
  199. if (\count($sequence) === ($sequenceKey + 1)) {
  200. break;
  201. }
  202. } elseif (self::METHOD_ARGUMENTS_TOKEN === $item) {
  203. $this->skipMethodArgument($tokenIterator);
  204. } elseif (self::DOMAIN_TOKEN === $item) {
  205. $domainToken = $this->getValue($tokenIterator);
  206. if ('' !== $domainToken) {
  207. $domain = $domainToken;
  208. }
  209. break;
  210. } else {
  211. break;
  212. }
  213. }
  214. if ($message) {
  215. $catalog->set($message, $this->prefix.$message, $domain);
  216. $metadata = $catalog->getMetadata($message, $domain) ?? [];
  217. $normalizedFilename = preg_replace('{[\\\\/]+}', '/', $filename);
  218. $metadata['sources'][] = $normalizedFilename.':'.$tokens[$key][2];
  219. $catalog->setMetadata($message, $metadata, $domain);
  220. break;
  221. }
  222. }
  223. }
  224. }
  225. /**
  226. * @param string $file
  227. *
  228. * @return bool
  229. *
  230. * @throws \InvalidArgumentException
  231. */
  232. protected function canBeExtracted($file)
  233. {
  234. return $this->isFile($file) && 'php' === pathinfo($file, PATHINFO_EXTENSION);
  235. }
  236. /**
  237. * @param string|array $directory
  238. *
  239. * @return array
  240. */
  241. protected function extractFromDirectory($directory)
  242. {
  243. $finder = new Finder();
  244. return $finder->files()->name('*.php')->in($directory);
  245. }
  246. }