CreatesPotentiallyTranslatedStrings.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace Illuminate\Translation;
  3. trait CreatesPotentiallyTranslatedStrings
  4. {
  5. /**
  6. * Create a pending potentially translated string.
  7. *
  8. * @param string $attribute
  9. * @param string|null $message
  10. * @return \Illuminate\Translation\PotentiallyTranslatedString
  11. */
  12. protected function pendingPotentiallyTranslatedString($attribute, $message)
  13. {
  14. $destructor = $message === null
  15. ? fn ($message) => $this->messages[] = $message
  16. : fn ($message) => $this->messages[$attribute] = $message;
  17. return new class($message ?? $attribute, $this->validator->getTranslator(), $destructor) extends PotentiallyTranslatedString
  18. {
  19. /**
  20. * The callback to call when the object destructs.
  21. *
  22. * @var \Closure
  23. */
  24. protected $destructor;
  25. /**
  26. * Create a new pending potentially translated string.
  27. *
  28. * @param string $message
  29. * @param \Illuminate\Contracts\Translation\Translator $translator
  30. * @param \Closure $destructor
  31. */
  32. public function __construct($message, $translator, $destructor)
  33. {
  34. parent::__construct($message, $translator);
  35. $this->destructor = $destructor;
  36. }
  37. /**
  38. * Handle the object's destruction.
  39. *
  40. * @return void
  41. */
  42. public function __destruct()
  43. {
  44. ($this->destructor)($this->toString());
  45. }
  46. };
  47. }
  48. }