PotentiallyTranslatedString.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. namespace Illuminate\Translation;
  3. use Stringable;
  4. class PotentiallyTranslatedString implements Stringable
  5. {
  6. /**
  7. * The string that may be translated.
  8. *
  9. * @var string
  10. */
  11. protected $string;
  12. /**
  13. * The translated string.
  14. *
  15. * @var string|null
  16. */
  17. protected $translation;
  18. /**
  19. * The validator that may perform the translation.
  20. *
  21. * @var \Illuminate\Contracts\Translation\Translator
  22. */
  23. protected $translator;
  24. /**
  25. * Create a new potentially translated string.
  26. *
  27. * @param string $string
  28. * @param \Illuminate\Contracts\Translation\Translator $translator
  29. */
  30. public function __construct($string, $translator)
  31. {
  32. $this->string = $string;
  33. $this->translator = $translator;
  34. }
  35. /**
  36. * Translate the string.
  37. *
  38. * @param array $replace
  39. * @param string|null $locale
  40. * @return $this
  41. */
  42. public function translate($replace = [], $locale = null)
  43. {
  44. $this->translation = $this->translator->get($this->string, $replace, $locale);
  45. return $this;
  46. }
  47. /**
  48. * Translates the string based on a count.
  49. *
  50. * @param \Countable|int|float|array $number
  51. * @param array $replace
  52. * @param string|null $locale
  53. * @return $this
  54. */
  55. public function translateChoice($number, array $replace = [], $locale = null)
  56. {
  57. $this->translation = $this->translator->choice($this->string, $number, $replace, $locale);
  58. return $this;
  59. }
  60. /**
  61. * Get the original string.
  62. *
  63. * @return string
  64. */
  65. public function original()
  66. {
  67. return $this->string;
  68. }
  69. /**
  70. * Get the potentially translated string.
  71. *
  72. * @return string
  73. */
  74. public function __toString()
  75. {
  76. return $this->translation ?? $this->string;
  77. }
  78. /**
  79. * Get the potentially translated string.
  80. *
  81. * @return string
  82. */
  83. public function toString()
  84. {
  85. return (string) $this;
  86. }
  87. }