blob: 08c8f899747ba6d04f6aa8ffab80b6ed6dc60f10 [file] [log] [blame]
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +02001<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Symfony\Component\Translation\Dumper;
13
14use Symfony\Component\Translation\Loader\MoFileLoader;
15use Symfony\Component\Translation\MessageCatalogue;
16
17/**
18 * MoFileDumper generates a gettext formatted string representation of a message catalogue.
19 *
20 * @author Stealth35
21 */
22class MoFileDumper extends FileDumper
23{
24 /**
25 * {@inheritdoc}
26 */
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +010027 public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []): string
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +020028 {
29 $sources = $targets = $sourceOffsets = $targetOffsets = '';
30 $offsets = [];
31 $size = 0;
32
33 foreach ($messages->all($domain) as $source => $target) {
34 $offsets[] = array_map('strlen', [$sources, $source, $targets, $target]);
35 $sources .= "\0".$source;
36 $targets .= "\0".$target;
37 ++$size;
38 }
39
40 $header = [
41 'magicNumber' => MoFileLoader::MO_LITTLE_ENDIAN_MAGIC,
42 'formatRevision' => 0,
43 'count' => $size,
44 'offsetId' => MoFileLoader::MO_HEADER_SIZE,
45 'offsetTranslated' => MoFileLoader::MO_HEADER_SIZE + (8 * $size),
46 'sizeHashes' => 0,
47 'offsetHashes' => MoFileLoader::MO_HEADER_SIZE + (16 * $size),
48 ];
49
50 $sourcesSize = \strlen($sources);
51 $sourcesStart = $header['offsetHashes'] + 1;
52
53 foreach ($offsets as $offset) {
54 $sourceOffsets .= $this->writeLong($offset[1])
55 .$this->writeLong($offset[0] + $sourcesStart);
56 $targetOffsets .= $this->writeLong($offset[3])
57 .$this->writeLong($offset[2] + $sourcesStart + $sourcesSize);
58 }
59
60 $output = implode('', array_map([$this, 'writeLong'], $header))
61 .$sourceOffsets
62 .$targetOffsets
63 .$sources
64 .$targets
65 ;
66
67 return $output;
68 }
69
70 /**
71 * {@inheritdoc}
72 */
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +010073 protected function getExtension(): string
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +020074 {
75 return 'mo';
76 }
77
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +010078 private function writeLong(mixed $str): string
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +020079 {
80 return pack('V*', $str);
81 }
82}