MoFileDumper.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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\Loader\MoFileLoader;
  12. use Symfony\Component\Translation\MessageCatalogue;
  13. /**
  14. * MoFileDumper generates a gettext formatted string representation of a message catalogue.
  15. *
  16. * @author Stealth35
  17. */
  18. class MoFileDumper extends FileDumper
  19. {
  20. public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []): string
  21. {
  22. $sources = $targets = $sourceOffsets = $targetOffsets = '';
  23. $offsets = [];
  24. $size = 0;
  25. foreach ($messages->all($domain) as $source => $target) {
  26. $offsets[] = array_map('strlen', [$sources, $source, $targets, $target]);
  27. $sources .= "\0".$source;
  28. $targets .= "\0".$target;
  29. ++$size;
  30. }
  31. $header = [
  32. 'magicNumber' => MoFileLoader::MO_LITTLE_ENDIAN_MAGIC,
  33. 'formatRevision' => 0,
  34. 'count' => $size,
  35. 'offsetId' => MoFileLoader::MO_HEADER_SIZE,
  36. 'offsetTranslated' => MoFileLoader::MO_HEADER_SIZE + (8 * $size),
  37. 'sizeHashes' => 0,
  38. 'offsetHashes' => MoFileLoader::MO_HEADER_SIZE + (16 * $size),
  39. ];
  40. $sourcesSize = \strlen($sources);
  41. $sourcesStart = $header['offsetHashes'] + 1;
  42. foreach ($offsets as $offset) {
  43. $sourceOffsets .= $this->writeLong($offset[1])
  44. .$this->writeLong($offset[0] + $sourcesStart);
  45. $targetOffsets .= $this->writeLong($offset[3])
  46. .$this->writeLong($offset[2] + $sourcesStart + $sourcesSize);
  47. }
  48. $output = implode('', array_map($this->writeLong(...), $header))
  49. .$sourceOffsets
  50. .$targetOffsets
  51. .$sources
  52. .$targets
  53. ;
  54. return $output;
  55. }
  56. protected function getExtension(): string
  57. {
  58. return 'mo';
  59. }
  60. private function writeLong(mixed $str): string
  61. {
  62. return pack('V*', $str);
  63. }
  64. }