string.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /**
  3. * Copyright (c) 2012 Bart Visscher <bartv@thisnet.nl>
  4. * This file is licensed under the Affero General Public License version 3 or
  5. * later.
  6. * See the COPYING-README file.
  7. */
  8. class OC_L10N_String{
  9. /**
  10. * @var OC_L10N
  11. */
  12. protected $l10n;
  13. /**
  14. * @var string
  15. */
  16. protected $text;
  17. /**
  18. * @var array
  19. */
  20. protected $parameters;
  21. /**
  22. * @var array
  23. */
  24. protected $plurals;
  25. /**
  26. * @var integer
  27. */
  28. protected $count;
  29. /**
  30. * @param OC_L10N $l10n
  31. */
  32. public function __construct($l10n, $text, $parameters, $count = 1, $plurals = array()) {
  33. $this->l10n = $l10n;
  34. $this->text = $text;
  35. $this->parameters = $parameters;
  36. $this->count = $count;
  37. $this->plurals = $plurals;
  38. }
  39. public function __toString() {
  40. $translations = $this->l10n->getTranslations();
  41. $text = $this->text;
  42. if(array_key_exists($this->text, $translations)) {
  43. if(is_array($translations[$this->text])) {
  44. $fn = $this->l10n->getPluralFormFunction();
  45. $id = $fn($this->count);
  46. if ($translations[$this->text][$id] !== '') {
  47. // The translation of this plural case is not empty, so use it
  48. $text = $translations[$this->text][$id];
  49. } else {
  50. // We didn't find the plural in the language,
  51. // so we fall back to english.
  52. $id = ($id != 0) ? 1 : 0;
  53. if (isset($this->plurals[$id])) {
  54. // Fallback to the english plural
  55. $text = $this->plurals[$id];
  56. }
  57. }
  58. }
  59. else{
  60. $text = $translations[$this->text];
  61. }
  62. }
  63. // Replace %n first (won't interfere with vsprintf)
  64. $text = str_replace('%n', $this->count, $text);
  65. return vsprintf($text, $this->parameters);
  66. }
  67. }