PoFileDumper.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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\Dumper;
  11. use Symfony\Component\Translation\MessageCatalogue;
  12. /**
  13. * PoFileDumper generates a gettext formatted string representation of a message catalogue.
  14. *
  15. * @author Stealth35
  16. */
  17. class PoFileDumper extends FileDumper
  18. {
  19. /**
  20. * {@inheritdoc}
  21. */
  22. public function formatCatalogue(MessageCatalogue $messages, $domain, array $options = [])
  23. {
  24. $output = 'msgid ""'."\n";
  25. $output .= 'msgstr ""'."\n";
  26. $output .= '"Content-Type: text/plain; charset=UTF-8\n"'."\n";
  27. $output .= '"Content-Transfer-Encoding: 8bit\n"'."\n";
  28. $output .= '"Language: '.$messages->getLocale().'\n"'."\n";
  29. $output .= "\n";
  30. $newLine = false;
  31. foreach ($messages->all($domain) as $source => $target) {
  32. if ($newLine) {
  33. $output .= "\n";
  34. } else {
  35. $newLine = true;
  36. }
  37. $metadata = $messages->getMetadata($source, $domain);
  38. if (isset($metadata['comments'])) {
  39. $output .= $this->formatComments($metadata['comments']);
  40. }
  41. if (isset($metadata['flags'])) {
  42. $output .= $this->formatComments(implode(',', (array) $metadata['flags']), ',');
  43. }
  44. if (isset($metadata['sources'])) {
  45. $output .= $this->formatComments(implode(' ', (array) $metadata['sources']), ':');
  46. }
  47. $output .= sprintf('msgid "%s"'."\n", $this->escape($source));
  48. $output .= sprintf('msgstr "%s"'."\n", $this->escape($target));
  49. }
  50. return $output;
  51. }
  52. /**
  53. * {@inheritdoc}
  54. */
  55. protected function getExtension()
  56. {
  57. return 'po';
  58. }
  59. private function escape($str)
  60. {
  61. return addcslashes($str, "\0..\37\42\134");
  62. }
  63. private function formatComments($comments, string $prefix = ''): ?string
  64. {
  65. $output = null;
  66. foreach ((array) $comments as $comment) {
  67. $output .= sprintf('#%s %s'."\n", $prefix, $comment);
  68. }
  69. return $output;
  70. }
  71. }