L10NString.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\L10N;
  8. class L10NString implements \JsonSerializable {
  9. /** @var L10N */
  10. protected $l10n;
  11. /** @var string */
  12. protected $text;
  13. /** @var array */
  14. protected $parameters;
  15. /** @var integer */
  16. protected $count;
  17. /**
  18. * @param L10N $l10n
  19. * @param string|string[] $text
  20. * @param array $parameters
  21. * @param int $count
  22. */
  23. public function __construct(L10N $l10n, $text, array $parameters, int $count = 1) {
  24. $this->l10n = $l10n;
  25. $this->text = $text;
  26. $this->parameters = $parameters;
  27. $this->count = $count;
  28. }
  29. public function __toString(): string {
  30. $translations = $this->l10n->getTranslations();
  31. $identityTranslator = $this->l10n->getIdentityTranslator();
  32. // Use the indexed version as per \Symfony\Contracts\Translation\TranslatorInterface
  33. $identity = $this->text;
  34. if (array_key_exists($this->text, $translations)) {
  35. $identity = $translations[$this->text];
  36. }
  37. if (is_array($identity)) {
  38. $pipeCheck = implode('', $identity);
  39. if (str_contains($pipeCheck, '|')) {
  40. return 'Can not use pipe character in translations';
  41. }
  42. $identity = implode('|', $identity);
  43. } elseif (str_contains($identity, '|')) {
  44. return 'Can not use pipe character in translations';
  45. }
  46. $beforeIdentity = $identity;
  47. $identity = str_replace('%n', '%count%', $identity);
  48. $parameters = [];
  49. if ($beforeIdentity !== $identity) {
  50. $parameters = ['%count%' => $this->count];
  51. }
  52. // $count as %count% as per \Symfony\Contracts\Translation\TranslatorInterface
  53. $text = $identityTranslator->trans($identity, $parameters);
  54. return vsprintf($text, $this->parameters);
  55. }
  56. public function jsonSerialize(): string {
  57. return $this->__toString();
  58. }
  59. }