IcuResFileDumper.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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. * IcuResDumper generates an ICU ResourceBundle formatted string representation of a message catalogue.
  14. *
  15. * @author Stealth35
  16. */
  17. class IcuResFileDumper extends FileDumper
  18. {
  19. /**
  20. * {@inheritdoc}
  21. */
  22. protected $relativePathTemplate = '%domain%/%locale%.%extension%';
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public function formatCatalogue(MessageCatalogue $messages, $domain, array $options = array())
  27. {
  28. $data = $indexes = $resources = '';
  29. foreach ($messages->all($domain) as $source => $target) {
  30. $indexes .= pack('v', strlen($data) + 28);
  31. $data .= $source."\0";
  32. }
  33. $data .= $this->writePadding($data);
  34. $keyTop = $this->getPosition($data);
  35. foreach ($messages->all($domain) as $source => $target) {
  36. $resources .= pack('V', $this->getPosition($data));
  37. $data .= pack('V', strlen($target))
  38. .mb_convert_encoding($target."\0", 'UTF-16LE', 'UTF-8')
  39. .$this->writePadding($data)
  40. ;
  41. }
  42. $resOffset = $this->getPosition($data);
  43. $data .= pack('v', count($messages))
  44. .$indexes
  45. .$this->writePadding($data)
  46. .$resources
  47. ;
  48. $bundleTop = $this->getPosition($data);
  49. $root = pack('V7',
  50. $resOffset + (2 << 28), // Resource Offset + Resource Type
  51. 6, // Index length
  52. $keyTop, // Index keys top
  53. $bundleTop, // Index resources top
  54. $bundleTop, // Index bundle top
  55. count($messages), // Index max table length
  56. 0 // Index attributes
  57. );
  58. $header = pack('vC2v4C12@32',
  59. 32, // Header size
  60. 0xDA, 0x27, // Magic number 1 and 2
  61. 20, 0, 0, 2, // Rest of the header, ..., Size of a char
  62. 0x52, 0x65, 0x73, 0x42, // Data format identifier
  63. 1, 2, 0, 0, // Data version
  64. 1, 4, 0, 0 // Unicode version
  65. );
  66. return $header.$root.$data;
  67. }
  68. private function writePadding($data)
  69. {
  70. $padding = strlen($data) % 4;
  71. if ($padding) {
  72. return str_repeat("\xAA", 4 - $padding);
  73. }
  74. }
  75. private function getPosition($data)
  76. {
  77. return (strlen($data) + 28) / 4;
  78. }
  79. /**
  80. * {@inheritdoc}
  81. */
  82. protected function getExtension()
  83. {
  84. return 'res';
  85. }
  86. }