Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.6] Ability to set locale on sent Mailable #23178

Merged
merged 3 commits into from
Feb 22, 2018
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/Illuminate/Mail/MailServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ protected function registerIlluminateMailer()
$mailer->setQueue($app['queue']);
}

if ($app->bound('translator')) {
$mailer->setTranslator($app['translator']);
}

// Next we will set all of the global addresses on this mailer, which allows
// for easy unification of all "from" addresses as well as easy debugging
// of sent messages since they get be sent into a single email address.
Expand Down
48 changes: 40 additions & 8 deletions src/Illuminate/Mail/Mailable.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,13 @@ class Mailable implements MailableContract, Renderable
*/
public $replyTo = [];

/**
* The locale of the message.
*
* @var string
*/
public $locale;

/**
* The subject of the message.
*
Expand Down Expand Up @@ -122,15 +129,27 @@ class Mailable implements MailableContract, Renderable
*/
public function send(MailerContract $mailer)
{
Container::getInstance()->call([$this, 'build']);
$currentLocale = $mailer->translator ? $mailer->translator->getLocale() : null;

$mailer->send($this->buildView(), $this->buildViewData(), function ($message) {
$this->buildFrom($message)
->buildRecipients($message)
->buildSubject($message)
->runCallbacks($message)
->buildAttachments($message);
});
try {
if ($mailer->translator && $this->locale) {
$mailer->translator->setLocale($this->locale);
}

Container::getInstance()->call([$this, 'build']);

$mailer->send($this->buildView(), $this->buildViewData(), function ($message) {
$this->buildFrom($message)
->buildRecipients($message)
->buildSubject($message)
->runCallbacks($message)
->buildAttachments($message);
});
} finally {
if ($mailer->translator) {
$mailer->translator->setLocale($currentLocale);
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would you have an interest in offering a ChangesLocale concerns trait that can be re-purposed in user-land?

trait ChangesLocale
{
    /**
     * @param \Illuminate\Contracts\Translation\Translator $translator
     * @param string                                       $locale
     * @param callable                                     $callback
     *
     * @return mixed
     */
    public function asLocale($translator, $locale, callable $callback)
    {
        if ($translator && $locale) {
            try {
                $currentLocale = $translator->getLocale();

                $translator->setLocale($locale);

                return $callback($locale);
            } finally {
                $translator->setLocale($currentLocale);
            }
        } else {
            return $callback($locale);
        }
    }
}

Then send() simplifies to:

public function send(MailerContract $mailer)
{
    $this->asLocale($mailer->translator, $this->locale, function () use ($mailer) {
        Container::getInstance()->call([$this, 'build']);

        $mailer->send($this->buildView(), $this->buildViewData(), function ($message) {
            $this->buildFrom($message)
                ->buildRecipients($message)
                ->buildSubject($message)
                ->runCallbacks($message)
                ->buildAttachments($message);
        });
    });
}

The trait I've been wrapping Mailer@send() with for awhile is much simpler when assuming a translator is bound to the app container:

trait ChangesLocale
{
    public function asLocale($locale, callable $callback)
    {
        try {
            $currentLocale = app()->getLocale();

            if ($locale) {
                app()->setLocale($locale);
            }

            return $callback($locale);
        } finally {
            if ($locale) {
                app()->setLocale($currentLocale);
            }
        }
    }
}

}

/**
Expand Down Expand Up @@ -572,6 +591,19 @@ protected function hasRecipient($address, $name = null, $property = 'to')
});
}

/**
* Set the locale of the message.
*
* @param string $locale
* @return $this
*/
public function locale($locale)
{
$this->locale = $locale;

return $this;
}

/**
* Set the subject of the message.
*
Expand Down
32 changes: 32 additions & 0 deletions src/Illuminate/Mail/Mailer.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Illuminate\Contracts\Queue\Factory as QueueContract;
use Illuminate\Contracts\Mail\Mailable as MailableContract;
use Illuminate\Contracts\Mail\MailQueue as MailQueueContract;
use Illuminate\Contracts\Translation\Translator as TranslatorContract;

class Mailer implements MailerContract, MailQueueContract
{
Expand Down Expand Up @@ -68,6 +69,13 @@ class Mailer implements MailerContract, MailQueueContract
*/
protected $queue;

/**
* The translator implementation.
*
* @var \Illuminate\Contracts\Translation\Translator
*/
public $translator;

/**
* Array of failed recipients.
*
Expand Down Expand Up @@ -148,6 +156,17 @@ public function bcc($users)
return (new PendingMail($this))->bcc($users);
}

/**
* Begin the process of mailing a mailable class instance.
*
* @param string $locale
* @return \Illuminate\Mail\PendingMail
*/
public function locale($locale)
{
return (new PendingMail($this))->locale($locale);
}

/**
* Send a new message with only an HTML part.
*
Expand Down Expand Up @@ -566,4 +585,17 @@ public function setQueue(QueueContract $queue)

return $this;
}

/**
* Set the translator instance.
*
* @param \Illuminate\Contracts\Translation\Translator $translator
* @return $this
*/
public function setTranslator(TranslatorContract $translator)
{
$this->translator = $translator;

return $this;
}
}
23 changes: 22 additions & 1 deletion src/Illuminate/Mail/PendingMail.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,13 @@ class PendingMail
*/
protected $bcc = [];

/**
* The locale of the message.
*
* @var array
*/
protected $locale;

/**
* Create a new mailable mailer instance.
*
Expand Down Expand Up @@ -84,6 +91,19 @@ public function bcc($users)
return $this;
}

/**
* Set the locale of the message.
*
* @param string $locale
* @return $this
*/
public function locale($locale)
{
$this->locale = $locale;

return $this;
}

/**
* Send a new mailable message instance.
*
Expand Down Expand Up @@ -149,6 +169,7 @@ protected function fill(Mailable $mailable)
{
return $mailable->to($this->to)
->cc($this->cc)
->bcc($this->bcc);
->bcc($this->bcc)
->locale($this->locale);
}
}
11 changes: 11 additions & 0 deletions src/Illuminate/Translation/Translator.php
Original file line number Diff line number Diff line change
Expand Up @@ -476,4 +476,15 @@ public function setFallback($fallback)
{
$this->fallback = $fallback;
}

/**
* Set loaded translation groups.
*
* @param string $fallback
* @return void
*/
public function setLoaded($loaded)
{
$this->loaded = $loaded;
}
}
1 change: 1 addition & 0 deletions tests/Integration/Mail/Fixtures/view.blade.php
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{{__('nom')}}
94 changes: 94 additions & 0 deletions tests/Integration/Mail/SendingMailWithLocaleTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<?php

namespace Illuminate\Tests\Integration\Mail\SendingMailWithLocale;

use Mockery;
use Illuminate\Mail\Mailable;
use Orchestra\Testbench\TestCase;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\View;

/**
* @group integration
*/
class SendingMailWithLocaleTest extends TestCase
{
public function tearDown()
{
parent::tearDown();

Mockery::close();
}

protected function getEnvironmentSetUp($app)
{
$app['config']->set('app.debug', 'true');

$app['config']->set('mail.driver', 'array');

$app['config']->set('app.locale', 'en');

View::addLocation(__DIR__.'/Fixtures');

app('translator')->setLoaded([
'*' => [
'*' => [
'en' => ['nom' => 'name'],
'ar' => ['nom' => 'esm'],
],
],
]);
}

public function setUp()
{
parent::setUp();
}

public function test_mail_is_sent_with_default_locale()
{
Mail::to('test@mail.com')->send(new TestMail());

$this->assertContains('name',
app('swift.transport')->messages()[0]->getBody()
);
}

public function test_mail_is_sent_with_selected_locale()
{
Mail::to('test@mail.com')->locale('ar')->send(new TestMail());

$this->assertContains('esm',
app('swift.transport')->messages()[0]->getBody()
);
}

public function test_locale_is_set_back_to_default_after_mail_sent()
{
Mail::to('test@mail.com')->locale('ar')->send(new TestMail());
Mail::to('test@mail.com')->send(new TestMail());

$this->assertEquals('en', app('translator')->getLocale());

$this->assertContains('esm',
app('swift.transport')->messages()[0]->getBody()
);

$this->assertContains('name',
app('swift.transport')->messages()[1]->getBody()
);
}
}

class TestMail extends Mailable
{
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->view('view');
}
}