TranslatableMessageVisitor.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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\Visitor;
  11. use PhpParser\Node;
  12. use PhpParser\NodeVisitor;
  13. use Symfony\Component\Translation\TranslatableMessage;
  14. /**
  15. * @author Mathieu Santostefano <msantostefano@protonmail.com>
  16. */
  17. final class TranslatableMessageVisitor extends AbstractVisitor implements NodeVisitor
  18. {
  19. public function beforeTraverse(array $nodes): ?Node
  20. {
  21. return null;
  22. }
  23. public function enterNode(Node $node): ?Node
  24. {
  25. return null;
  26. }
  27. public function leaveNode(Node $node): ?Node
  28. {
  29. if (!$node instanceof Node\Expr\New_) {
  30. return null;
  31. }
  32. if (!($className = $node->class) instanceof Node\Name) {
  33. return null;
  34. }
  35. // the name resolver gives a fully qualified name; templates without a "use"
  36. // statement resolve to the global namespace, which is accepted as well
  37. if (!\in_array($className->toString(), [TranslatableMessage::class, 'TranslatableMessage'], true)) {
  38. return null;
  39. }
  40. $firstNamedArgumentIndex = $this->nodeFirstNamedArgumentIndex($node);
  41. if (!$messages = $this->getStringArguments($node, 0 < $firstNamedArgumentIndex ? 0 : 'message')) {
  42. return null;
  43. }
  44. $domain = $this->getStringArguments($node, 2 < $firstNamedArgumentIndex ? 2 : 'domain')[0] ?? null;
  45. foreach ($messages as $message) {
  46. $this->addMessageToCatalogue($message, $domain, $node->getStartLine());
  47. }
  48. return null;
  49. }
  50. public function afterTraverse(array $nodes): ?Node
  51. {
  52. return null;
  53. }
  54. }