Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame^] | 1 | <?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 | |
| 12 | namespace Symfony\Component\Translation\Dumper; |
| 13 | |
| 14 | use Symfony\Component\Translation\Loader\MoFileLoader; |
| 15 | use Symfony\Component\Translation\MessageCatalogue; |
| 16 | |
| 17 | /** |
| 18 | * MoFileDumper generates a gettext formatted string representation of a message catalogue. |
| 19 | * |
| 20 | * @author Stealth35 |
| 21 | */ |
| 22 | class MoFileDumper extends FileDumper |
| 23 | { |
| 24 | /** |
| 25 | * {@inheritdoc} |
| 26 | */ |
| 27 | public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []) |
| 28 | { |
| 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 | */ |
| 73 | protected function getExtension() |
| 74 | { |
| 75 | return 'mo'; |
| 76 | } |
| 77 | |
| 78 | private function writeLong($str): string |
| 79 | { |
| 80 | return pack('V*', $str); |
| 81 | } |
| 82 | } |