Mailer.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace Tools\Mailer;
  3. use Cake\Core\Configure;
  4. use Cake\I18n\I18n;
  5. use Cake\Mailer\Mailer as CakeMailer;
  6. /**
  7. * Allows locale overwrite to send emails in a specific language
  8. */
  9. class Mailer extends CakeMailer {
  10. /**
  11. * @var string
  12. */
  13. protected $locale;
  14. /**
  15. * @inheritDoc
  16. */
  17. public function send($action, $args = [], $headers = []) {
  18. $this->fixateLocale();
  19. $result = parent::send($action, $args, $headers);
  20. $this->restoreLocale();
  21. return $result;
  22. }
  23. /**
  24. * Switch to primary locale if applicable.
  25. *
  26. * @return void
  27. */
  28. protected function fixateLocale() {
  29. $this->locale = I18n::locale();
  30. $primaryLocale = $this->getPrimaryLocale();
  31. if ($primaryLocale && $primaryLocale !== $this->locale) {
  32. I18n::locale($primaryLocale);
  33. }
  34. }
  35. /**
  36. * Restore to current locale if applicable.
  37. *
  38. * @return void
  39. */
  40. protected function restoreLocale() {
  41. $primaryLocale = $this->getPrimaryLocale();
  42. if ($primaryLocale && $primaryLocale !== $this->locale) {
  43. I18n::locale($this->locale);
  44. }
  45. }
  46. /**
  47. * Returns the configured default locale.
  48. *
  49. * Can be based on the primary language and the allowed languages (whitelist).
  50. *
  51. * @return string
  52. */
  53. protected function getPrimaryLocale() {
  54. $primaryLanguage = Configure::read('Config.defaultLanguage');
  55. if (Configure::read('Config.defaultLocale')) {
  56. return Configure::read('Config.defaultLocale');
  57. }
  58. $primaryLocale = Configure::read('Config.allowedLanguages.' . $primaryLanguage . '.locale');
  59. return $primaryLocale;
  60. }
  61. }